C++ Numbers and Strings

πŸ”’πŸ§΅ C++ Numbers and Strings

C++ mein numbers (int, float, double) aur strings (text) ko saath use karna common hai.
Neeche print, concatenate, convert, inputβ€”sab clear examples ke saath samjhaaya gaya hai.


πŸ”Ή 1. Numbers vs Strings (Basic Difference)

int a = 10;
string b = "10";
  • a β†’ number (math possible)

  • b β†’ string (text)

cout << a + a; // 20
cout << b + b; // 1010

πŸ”Ή 2. Print Number with String

int age = 20;
cout << "Age: " << age;

Output:

Age: 20

πŸ”Ή 3. Concatenate String with Number ❌ (Directly)

string s = "Age: " + 20; // ❌ Error

βœ” Correct (Use to_string)

string s = "Age: " + to_string(20);
cout << s;

πŸ”Ή 4. Convert Number β†’ String (to_string)

int x = 50;
string s = to_string(x);
double pi = 3.14;
string p = to_string(pi);

πŸ”Ή 5. Convert String β†’ Number

πŸ”Έ stoi (string β†’ int)

string s = "123";
int x = stoi(s); // 123

πŸ”Έ stof (string β†’ float)

string s = "3.14";
float f = stof(s);

πŸ”Έ stod (string β†’ double)

string s = "2.718";
double d = stod(s);

πŸ”Ή 6. Math with Converted Strings

string a = "10";
string b = "20";
int sum = stoi(a) + stoi(b);
cout << sum; // 30


πŸ”Ή 7. User Input: Number + String

int age;
string name;
cout << “Enter age: “;
cin >> age;
cin.ignore(); // important
cout << “Enter name: “;
getline(cin, name);

cout << name << ” is “ << age << ” years old”;


πŸ”Ή 8. String with Digits (Still String!)

string s = "123";
cout << s + "4"; // 1234

To calculate:

cout << stoi(s) + 4; // 127

❌ Common Mistakes

cout << "Sum = " + 10 + 20; // ❌ wrong

βœ” Correct:

cout << "Sum = " << 10 + 20;

πŸ“Œ Summary

  • Numbers β†’ math operations

  • Strings β†’ text operations

  • to_string() : number β†’ string

  • stoi / stof / stod : string β†’ number

  • Direct string + number ❌ (convert first)

You may also like...