C++读取含空格字符串后输出丢失首字符原因咨询
Hey there, let's figure out why your input and output don't match here.
First, let's recap your code:
cin.ignore(); string s; getline(cin,s); cout<<s<<endl;
And the behavior you're seeing:
Input:
gee ks for gee ks
Output:ee ks for gee ks
The Root Cause
The problem lies with the cin.ignore() line. By default, cin.ignore() only skips one single character from the input buffer.
Here's what's happening:
- If you ran this code without any prior input operations (meaning the input buffer is empty), the first character you type (the
gingee) gets caught and discarded bycin.ignore(). That's exactly why your output starts witheeinstead ofgee. - If you did have a prior input (like using
cin >>to read a number or a word without spaces), the buffer would have a leftover newline character (\n) from when the user pressed enter. In that case,cin.ignore()would skip that newline—but only if that's the first character in the buffer. If there's anything else (like accidental leftover characters), it'll still skip the first one regardless.
How to Fix It
To safely clear the input buffer up to the newline (which is usually what you want when mixing cin >> and getline), use this instead of plain cin.ignore():
#include <iostream> #include <string> #include <limits> // Don't forget this header! int main() { // If you had prior input like: int num; cin >> num; cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Clears everything until the newline string s; getline(cin, s); cout << s << endl; return 0; }
This line tells cin to ignore as many characters as needed (numeric_limits<streamsize>::max() represents the maximum number of characters the buffer can hold) until it hits a newline character (\n), which it also skips. That way, you won't accidentally eat the first character of your actual input.
If this code is the very first input operation in your program, you don't need any cin.ignore() at all—just call getline directly, since the input buffer is empty to begin with.
内容的提问来源于stack exchange,提问作者ranjan burnwal

