字符串find()函数的正确实现



我正试图将doubles推送到一个堆栈,给定stdin中的字符串,直到EOF。字符串可以由双精度、int、字符和单个空格组成。

目前,我正在使用substring和find((函数来解释空白。它在大多数情况下都能工作,但对于读取单个int的各种输入(如下所示(,find((函数似乎会破坏任何尾随的char。

我尝试过使用各种不同的字符串函数来尝试并重新实现解析输入的方式,但都并没有成功。

while(std::getline(std::cin, string, 'n')){
for(unsigned int x = 0; x < string.size(); x++){
std::cout << "You read " << string[x] << std::endl;
if(isdigit(string[x])){
do{
// Get the number, stopping at the first instance of ws
std::string get_str = string.substr(x, string.find(' '));
std::cout << "You're converting " << get_str << std::endl;
// Convert it to a double
double num = stod(get_str);
std::cout << "You pushed " << number << std::endl;
// Push it to the stack
stack.push(number);
// Get the new increment
std::cout << "The size is " << get_str.size() << std::endl;
x+= get_str.size();
} while(string[x] >= '0' && string[x] <= '9');
}
/* else, do other things... */

给定的输入

100 200 + 2 /

输出为:

You read 1
You're converting 100
You pushed 100
The size is 3
You read 2
You're converting 200
You pushed 200
The size is 3
You read +
You read  
You read 2
You're converting 2 /
You pushed 2
The size is 3

具体地说,我想知道当我在代码中使用string.find(' ')作为分隔符时,为什么从第三行到最后一行的'You're converting 2 / '包含"/"。考虑到这个问题,我该如何修复它,以便只有2个被"转换"?

感谢您的帮助和反馈!

一个参数find将在字符串的开头开始搜索,并返回匹配字符的索引。substr的第二个参数是字符数。把这些和你的输入放在一起,你会得到一个有3个字符的子字符串。

最新更新