在 c++ 中逐个字符从字符串传递到 int 时不精确
Imprecision when passing from string to int character by character in c++
首先,我从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;
相关文章:
- 给出不精确答案的递归Karatsuba算法
- 在 c++ 中逐个字符从字符串传递到 int 时不精确
- 为什么 cin.get(char, int) 不会溢出?
- 使用 c++ 时从二进制文件中读取 int 不正确
- 将向量的大小()转换为 int 不起作用
- 错误:成员引用基类型"uint32_t"(也称为"无符号 INT")不是结构或联合
- 为什么在调用 memcpy 到 bool 值后 memcpy 到 int 不起作用
- 称为对象类型"void (B::*)(int)"不是函数或函数指针
- C++错误:与调用'(std::list<int>) (int&)'不匹配
- 为什么 std::list<string> 有效,但 std::list <int>不起作用
- 为什么int不需要是常量和/或在函数中通过引用传递
- C++ printf 字段宽度说明符“.*”期望 int 不size_t
- 为什么一个简单的bimap(std::string <-> int)不起作用?
- C#/.NET定时器和Win32睡眠函数都是不精确的
- C++ 成员引用基类型'int'不是结构或联合
- OpenCV:错误:与调用'(cv::Mat) (int&, int&)'不匹配
- 为什么多头int不是100%准确?
- 浮点常量不精确的警告
- 如何在<int>不重建数组的情况下将 vector<vector> 转换为 int**?
- 为什么我会收到错误'A<int>'不是基类的基类的可访问'S<int>'基?