c++ - 在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++;
}
我想知道我的计算机是否有错误或者我遗漏了什么。
解决方案
首先,我从geline(cin, s) 中获取字符串,输入格式为:100 49。
然后最简单的解决方案是使用std::istringstream
:
int i1 = 0, i2 = 0;
std::istringstream( s ) >> i1 >> i2;
推荐阅读
- javascript - 异步函数返回一个承诺数组而不是实际的值数组
- python - 在正则表达式中查找出现数字(5-10)的情况
- json - org.json.JSONObject 将数字转换为指数形式
- intellij-idea - 是否有允许从现有代码创建新的单独文件的 IntelliJ 操作或快捷方式
- sequelize.js - 如何使用流类型正确注释 Sequelize 模型?
- javascript - d3 - 访问我点击的区域后面的数据
- jira - 如何在 Jira 票证中突出显示内联代码/文本?
- javascript - JS在有边距的画布上绘制时使用错误的坐标
- c++ - 有人可以解释速记赋值运算符的实际工作原理吗?
- c# - 如果它们重复并且需要全部输出,如何输出最大的数组元素