首页 > 解决方案 > 在c ++中逐个字符从字符串传递到int时不精确

问题描述

首先,我从 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++;
}

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

标签: c++type-conversionintcharacter

解决方案


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

然后最简单的解决方案是使用std::istringstream

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

推荐阅读