๐
Date: Jan 27, 2026
๐ฅ Topic: String Input Issues (getline) & Mutable Logic
๐ซ The Bug with 'cin'
I encountered a major issue today. I tried to input my full name "Sahil Tiwari" using cin.
Result: It only stored "Sahil".
Reason: cin stops reading as soon as it sees a SPACE or Enter.
✅ The Solution: getline()
To read a whole line (including spaces), we use the getline() function.
string fullName;
getline(cin, fullName); // Reads entire line
๐ง Mutable vs Immutable
In some languages (like Java/Python), strings are Immutable (cannot be changed once created).
Good News: In C++, Strings are Mutable. I can change any character directly.
string s = "Hello";
s[0] = 'J';
// s becomes "Jello". Easy!
๐ป Day 27 Code: Input Fix
#include <iostream>
#include <string>
using namespace std;
int main() {
string sentence;
cout << "Enter a sentence: ";
// cin >> sentence; // This would FAIL on spaces
getline(cin, sentence); // This WORKS
cout << "You typed: " << sentence << endl;
return 0;
}
๐ญ Thoughts
Using getline is essential for competitive programming when input formats are tricky. This marks the end of my String basics. Tomorrow, I start solving classic logic problems!
No comments:
Post a Comment