在 c++ 中逐个字符从字符串传递到 int 时不精确

Imprecision when passing from string to int character by character in c++

本文关键字:int 不精确 字符串 c++ 字符      更新时间:2023-10-16

首先,我从geline(cin,s(中获取字符串,输入的形式为:100 49。而且我不能用普通的 cin 接受它,因为我需要知道 geline(cin, s( 在哪里使 s 为空,所以这意味着是一个空行,我应该停止程序。 当从字符串'99'(或任何其他低于100的数字(传递到int 99时,没有问题。但是当我尝试一个大于 99 的数字时,它给出了(数字 - 1(。我还发现这种情况发生在低于 1000 的数字中,但从 1000 到 10000 没关系,但我测试了大于 10^4 的数字,它又给了(数字 - 1(。 这是我转换字符串的代码

//Search how many nums are in the string wer are passing until an space or new line
int nums = 0;
for(int j = i; j < s.size(); j++){
if(s[j] == ' ' || s[j] == 'n') break;
nums++;
}
//pass to the variable time the string character by character
int time = 0;
while(nums--){
time += (s[i] - '0') * (pow(10, nums));
i++;
}

我想知道我的计算机是否有错误或我错过了什么。

首先,我从 geline(cin, s( 中获取字符串,输入的形式为:100 49。

那么最简单的解决方案是使用std::istringstream

int i1 = 0, i2 = 0;
std::istringstream( s ) >> i1 >> i2;