Skip to main content

2. C++ Basics: Essential Differences from C

2.1 Basic Syntax Differences

C vs C++ Comparison:

Feature C C++
File Extension .c .cpp
Input/Output scanf(), printf() cin, cout
Header Files #include <stdio.h> #include <iostream>
Namespace Not used using namespace std;
Comments /* */ and // /* */ and // (preferred)
Boolean Type int (0/1) bool (true/false)
String Type char[] string class

2.2 Hello World Comparison

C Program:

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

C++ Program:

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}

2.3 Input/Output in C++

Basic I/O Operations:

#include <iostream>
using namespace std;

int main() {
    int age;
    string name;
    float height;
    
    // Output (cout with insertion operator <<)
    cout << "Enter your name: ";
    
    // Input (cin with extraction operator >>)
    cin >> name;
    
    cout << "Enter your age: ";
    cin >> age;
    
    cout << "Enter your height (m): ";
    cin >> height;
    
    // Multiple outputs
    cout << "Name: " << name << endl;
    cout << "Age: " << age << " years" << endl;
    cout << "Height: " << height << " meters" << endl;
    
    return 0;
}

C vs C++ I/O Comparison:

Operation C C++
Output integer printf("%d", x); cout << x;
Output float printf("%.2f", x); cout << fixed << setprecision(2) << x;
Output string printf("%s", str); cout << str;
Input integer scanf("%d", &x); cin >> x;
Input string scanf("%s", str); cin >> str;
Multiple inputs scanf("%d %d", &a, &b); cin >> a >> b;

Reading a Full Line:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string fullName;
    
    cout << "Enter your full name: ";
    getline(cin, fullName);  // Reads entire line including spaces
    
    cout << "Hello, " << fullName << "!" << endl;
    return 0;
}

Important Note on cin Buffer:

int age;
string name;

cin >> age;          // User enters "25" and presses Enter
// Buffer now contains the newline character

cin.ignore();        // Clear the newline from buffer
getline(cin, name);  // Now can read full line properly