[英]C++ // Compare getline input to a multiple word string?
How do you compare something you get from "getline(cin, fistName);" 您如何比较从“ getline(cin,fistName);”获得的内容? to a string "John Doe".
到字符串“ 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
您可以在这里阅读有关内容String Compare
So, my problem that wasn't initially shared in the code above, was that I was using cin above getline. 因此,我的问题最初并未在上面的代码中共享,是我在getline上使用了cin。 As I understand it now, cin 'grabs' the input and leaves the /n or 'enter' in the stream.
据我所知,cin“抓取”输入并将/ n或“ enter”留在流中。 So, just the /n registers and the user misses the opportunity to input their name as in the case above.
因此,仅/ n注册,用户就错过了输入姓名的机会,就像上面的情况一样。
I resolved this by avoiding the use of cin and using getline. 我通过避免使用cin和使用getline解决了这一问题。 Also, I got around this by using cin.ignore() after using cin if it was followed by a getline.
另外,如果使用cin.ignore()并紧随其后的是getline,则可以通过使用cin.ignore()来解决此问题。
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. 此外,您可以像上面的代码一样将getline值与equals运算符进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.