简体   繁体   中英

C++ first character does not print out using getline

After i run this code, it will prompt me to enter the first path eg c:/hello, and enter second path eg c:/world.

Output:

  • First path: c:/hello
  • Second path: :/world

As you can see the second path missing ac in front. But after i remove cin.get() after cout<<"Enter second path: "; it able to show the c in front. Can someone explain to me why is that so?

system("cls");
cout << "Enter first path: ";
cin.get();
getline(cin, firstPath);
cout << endl;
cout << "First path: " << firstPath << endl;
cout << endl;
cout << "Enter second path: ";
//cin.get(); // Need to be remove to shows c:/world
getline(cin, second path);
cout << endl;
cout << "Second path: " << secondPath<< endl;
cout << endl;
system("pause")
system("cls");

TL:DR; delete your cin.get(); lines


Delete cin.get(); it will read one character from cin , and so the next read from cin will read the next characters, so in the second case the "c" is being read by cin.get() and hence the next read, getline(cin, second path) will not read it (it has already been read). Why the "c" is being read after the first use of cin.get() is a mystery (perhaps you are typing a space before the "c"?

Only use cin.get() if you want to get the next character on the input stream and store it somewhere (eg char c = cin.get() , in this case c == 'c' ). If you want to skip the current character use cin.ignore() which does the same thing as cin.get() , except you can choose how many characters to skip, and it doesn't bother returning any read characters. Either way it would be inappropriate to use these in this situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM