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
string.find(" ") is not finding spaces
提问by TheHHHH
I'm trying to find space in a string that a user inputs. I want to use find()
from std::string
to 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 >> inputString
stops on whitespace...).
你不是在阅读空格(cin >> inputString
停在空格上......)。
Use std::getline(std::cin, inputString)
instead.
使用std::getline(std::cin, inputString)
来代替。
回答by masoud
It's because of cin
which truncates words after first space and store it to inputString
:
这是因为cin
which 在第一个空格后截断单词并将其存储到inputString
:
string inputString;
getline(cin, inputString);
int spac = inputString.find(" " , 0);
cout << spac << endl;