C++ string.find(" ") 没有找到空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15475744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:24:48  来源:igfitidea点击:

string.find(" ") is not finding spaces

c++string

提问by TheHHHH

I'm trying to find space in a string that a user inputs. I want to use find()from std::stringto return the position of the space.

我试图在用户输入的字符串中找到空格。我想用find()fromstd::string来返回空间的位置。

If the input is "Seattle, WA USA", and I want find(" ", 0)to return 8, how would I do this? 8th is the space after ","

如果输入是“Seattle, WA USA”,我想find(" ", 0)返回8,我该怎么做?第 8 个是“,”后的空格

string inputString = " ";
cout << "Enter String to modify" << endl;
cin >> inputString;
int spac = inputString.find(" " , 0);

But find()is keep returning 0. I am not sure why.

而是find()不断地返回0。我不知道为什么。

回答by sehe

You're not reading the space (cin >> inputStringstops on whitespace...).

你不是在阅读空格(cin >> inputString停在空格上......)。

Use std::getline(std::cin, inputString)instead.

使用std::getline(std::cin, inputString)来代替。

回答by masoud

It's because of cinwhich truncates words after first space and store it to inputString:

这是因为cinwhich 在第一个空格后截断单词并​​将其存储到inputString

string inputString;

getline(cin, inputString);

int spac = inputString.find(" " , 0);

cout << spac << endl;