简体   繁体   English

比较字符串不适用于cin

[英]Compare string doesnt work with cin

I am working on a trivial problem, but I cant figure it out. 我正在研究一个小问题,但是我无法弄清楚。 The program should put out the part after "simon says" if the beginning of str1 is "simon says". 如果str1的开头是“ simon say”,则程序应在“ simon say”之后放出一部分。 if i run it like in the following code, it works, but if i enter the string over cin >> str1; 如果我像下面的代码一样运行它,则可以,但是如果我在cin >> str1;输入字符串cin >> str1; myself, it doesnt. 我自己,它没有。 Does anybody have a tip for me? 有人给我小费吗? (and yes, this is a kattis problem) (是的,这是一个凯蒂斯问题)

int main()
{
 string str1("simon says write a program");
 //cin >> str1;
 string str2 ("simon says");
 if (str1.compare(0,10,str2,0,10) == 0){
  cout << str1.substr(11,str1.size());
 }
 return 0;
}

It's because std::cin gets whitespace-separated strings. 这是因为std :: cin获得了空格分隔的字符串。 If you will try to read a string from the standard input using 如果您尝试使用以下命令从标准输入中读取字符串

std::cin << str1;
// something here
std::cin << str2;

And you will enter "simon says", "simon" will land in the str1 and "says" will go to the str2. 您将输入“ simon说”,“ simon”将进入str1,“ says”将进入str2。 To read a whole line you should use 要阅读整行,您应该使用

std::getline()

With using cin >> str1 , if you print str1 for the sentence "Simon write something", you will see that str1 has the value "Simon". 使用cin >> str1 ,如果将str1打印为“ Simon写点东西”,您将看到str1的值为“ Simon”。

To not cut the sentence to the first space, Replace cin >> str1 by getline(cin, str1) 要不将句子切到第一个空格,请用getline(cin, str1)替换cin >> str1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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