C++ User Input Strings

⌨️ C++ User Input Strings

C++ mein string (text) input lene ke liye mainly do tarike hote hain:

1️⃣ cin
2️⃣ getline()


🔹 1. String Input Using cin

#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cin >> name;
cout << name;
return 0;
}

⚠️ Limitation

  • cin space ke baad input nahi leta

Input:

Ram Kumar

Output:

Ram

🔹 2. String Input Using getline() (Recommended)

string fullName;
getline(cin, fullName);
cout << fullName;

✔ Space ke saath poori line read karta hai


🔹 3. cin + getline() Problem

int age;
string name;
cin >> age;
getline(cin, name); // ❌ skip ho jayega

✔ Fix (Important)

cin >> age;
cin.ignore();
getline(cin, name);

🔹 4. Prompt ke Saath Input

string city;
cout << "Enter city: ";
getline(cin, city);

🔹 5. Multiple String Inputs

string first, last;
getline(cin, first);
getline(cin, last);

🔹 6. User Input + Output Example

#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;

cout << “Enter your name: “;
getline(cin, name);

cout << “Enter your age: “;
cin >> age;

cout << “Hello “ << name << “, Age: “ << age;
return 0;
}


🔹 7. Read Character-wise String (Advanced)

string s;
getline(cin, s);
for (char c : s) {
cout << c << ” “;
}


❌ Common Mistakes

cin << name; // ❌ wrong operator

✔ Correct:

cin >> name;

📌 Summary

  • cin → single word input

  • getline() → full line input

  • cin.ignore() → buffer issue fix

  • Strings ke saath getline() best choice

You may also like...