gpt4 book ai didi

c++ - 我正在使用C++,需要帮助来识别代码中的错误

转载 作者:行者123 更新时间:2023-12-02 10:22:17 25 4
gpt4 key购买 nike

我的outfile似乎正在正确写入,但是infile正在读取垃圾值。

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
int count;

ifstream infile;
infile.open("accounts.txt");

ofstream outfile;
outfile.open("accounts.txt");

cout<<"Read from file"<<endl;
infile>>count;
cout<<count<<endl;
cout<<"Write in file"<<endl;
outfile<<count;
cout<<count;

infile.close();
outfile.close();
return 0;
}

输出如下:
Read from file
4255273
Write in file
4255273

最佳答案

您的代码正在尝试同时打开和访问同一文件,作为输入流和输出流。这行不通!

您应该重新排列代码,以便将其打开以进行输入,进行输入,然后将其关闭。只有这样,您才能重新打开它以进行输出。

这是一个建议:

int main()
{
int count;

ifstream infile;
infile.open("accounts.txt"); // First, open for input...
cout << "Read from file" << endl;
infile >> count; // ... and read the data
cout << count << endl;
infile.close(); // Done reading: close it!

ofstream outfile;
outfile.open("accounts.txt"); // Now, open for output...
cout << "Write in file" << endl;
outfile << count; // ... do the output...
cout << count;
outfile.close(); // ... and close it.

return 0;
}

关于c++ - 我正在使用C++,需要帮助来识别代码中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59588564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com