gpt4 book ai didi

c++ - 没有正确读取字符串

转载 作者:可可西里 更新时间:2023-11-01 18:20:29 25 4
gpt4 key购买 nike

我正在练习用户输入处理。我的目标是让用户输入一行由空格(“”)分隔的整数,将它们作为整数读取,存储它们并在以后处理它们。我偶然发现了一个有趣的问题(我认为至少是)我这样做的方式,似乎它总是没有读取用户输入的最后一位数字。我将在此处发布整个程序(因为包含一些额外的库)。我在程序中留下了一些评论

#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>

using namespace std;

int main()
{
//this vector will store the integers
vector<int> a;
// this will store the user input
string inp;
getline(cin, inp);
// this string will temporarily store the digits
string tmp;
//be sure that the reading part is okay
cout << inp << endl;
//until you meet something different than a digit, read char by char and add to string
for(int i = 0; i < inp.length(); i++)
{
if(isdigit(inp[i]))
{
tmp +=inp[i];
}
else
{
// when it is not a character, turn to integer, empty string
int value = atoi(tmp.c_str());
a.push_back(value);
tmp = "";
}
}
// paste the entire vector of integers
for(int i = 0; i < a.size(); i++)
{
cout << a[i] << endl;
}
return 0;
}

最佳答案

替换这一行

for(int i = 0; i <inp.length(); i++)

for(int i = 0; i <= inp.length(); i++)

演示 IDEONE

您的代码的问题是:在示例中 25 30 46每当 i=7tmp=46你不是在 vector 中插入 46 作为 inp[8]是一个换行符,所以你的 for 循环在 i 变成 7 后终止。

请注意:i <= inp.length() 在大多数编译器中运行完美,因为\0 被用作/处理为哨兵。但是,很少有编译器(如 Microsoft Visual C++) 可能会显示断言错误:字符串下标超出范围。

关于c++ - 没有正确读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16061671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com