0
What is the problem with this code?
#include<iostream> #include<sstream> #include<string> using namespace std; int main() { string str = ""; int n; cin >> n; cin.ignore(); for(int i = 0; i < n; i++) { string name, first, last; getline(cin, name); stringstream ss(name); ss >> first >> last; str += first[0]; str += last[0]; if(i < n-1) { str += " "; } } cout << str << endl; return 0; }
2 Antworten
0
Hey,
The code works as expected. But the line ` for(int i = 0; i < n; i++) {` seems to contain some invalid characters (shows up for me as <200c>).
That's likely why u are getting the error.
0
The primary problem with the provided code is the cin.ignore() call immediately after cin >> n;. When cin >> n; reads the integer, it leaves the newline character in the input buffer. The subsequent cin.ignore() consumes one character, which is indeed that newline. However, if the user inputs n and then presses Enter, there's only one newline. If there's any other whitespace after n before the newline, cin.ignore() might not consume the intended character. A more robust approach for discarding the rest of the line after reading an integer is cin.ignore(numeric_limits<streamsize>::max(), '\n');. Without this, the first getline(cin, name); in the loop might read an empty string if there were extra characters or another newline left in the buffer from the integer input. Also, first[0] and last[0] could cause a crash if first or last are empty strings (e.g., if the user enters only a single name or an empty line).