简体   繁体   中英

C++ // Compare getline input to a multiple word string?

How do you compare something you get from "getline(cin, fistName);" to a string "John Doe".

Something like:

#include <string>

main() {
int x;
cin >> x;

string fullName;
getline(cin, fullName);
if(fullName == "John Doe")
    // some code;
}

Once you have two strings you can use its compare function. You can read about it here String Compare

  • change "get" to "getline" in your code, after changing your code will work fine. Instead of using "==" you can also use fullName.compare("John Deo").

So, my problem that wasn't initially shared in the code above, was that I was using cin above getline. As I understand it now, cin 'grabs' the input and leaves the /n or 'enter' in the stream. So, just the /n registers and the user misses the opportunity to input their name as in the case above.

I resolved this by avoiding the use of cin and using getline. Also, I got around this by using cin.ignore() after using cin if it was followed by a getline.

main(){

string x,y;
cin >> x;
cin.ignore();
getline(cin, y);
if (x == y) {
//some code
}


}

Additionally, you can compare the getline value with the equals operator like in the code above.

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