每次我通过ifstream读取一个特定的输入时,输入就会改变,可能是int溢出

Everytime I read in through ifstream for a specific input, the input changes, possible int overflow

本文关键字:输入 改变 int 溢出 ifstream 读取 一个      更新时间:2023-10-16

每次我使用ifstream作为程序的大输入时,我都会得到一些奇怪的东西。我有一种感觉,这与整数溢出有关,但我的程序仍然不能处理unsigned long long。下面是我的代码的简化版本,仍然显示错误:

#include <iostream>
#include <fstream>
using namespace std;
int main(){
    ofstream fout ("namenum.out");
    ifstream fin ("namenum.in");
    unsigned long long serial;
    fin >> serial;
    ifstream myReadFile;
    cout << serial << endl;
    return 0;
}

下面是奇怪的输入(或较大的输入):

5747867437

下面是我从cout得到的输出:

1452900141

我不知道是什么原因造成的。

这是我以前几乎没有给过的建议:总是检查你的输入在你试图阅读之后(感觉,我只给过这个建议几千次,所以很容易错过)。流无法预测你要读的内容,所以要确保它能正常工作:

if (fin >> searial) {
    fout << serial << 'n';
}
else {
    std::cerr << "failed to read the valuen";
}

查看您的代码,我大约100%肯定文件未打开(即流在尝试读取之前处于坏状态)或声称的内容不在文件中。

首先,您提供的数字肯定在unsigned long long的限制之内。其次,在unsigned long long中使用>>需要c++ 11的支持。c++ 0x支持unsigned long.

我复制了你的代码并创建了一个名为namenum的文件。在namenum中输入"5747867437"。使用UTF8编码

那么输出恰好是5747867437