我的C++代码有些问题。
当我运行此代码时:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string s;
string line;
fstream file("file.txt", ios::out | ios::in | ios::app);
cout << "enter your text :";
cin >> s;
file << s;
cout << "ndata file contains :";
while(getline(file, line))
{
cout << "n" << line;
}
cout << "n";
system("pause");
return 0;
}
输出应为:
输入您的文本 : alikamel//例如然后将其写入文件数据文件包含://文件内容
但我得到这个:
输入您的文本:屁股//例如并将其写入文件然后显示数据文件包含://什么都没有??
为什么它不显示文件内容,这是怎么回事?
您的问题是您正在尝试从文件末尾读取。
fstream
保存指向文件中当前位置的指针。完成对文件的写入后,此指针指向末尾,准备执行下一个写入命令。
因此,当您尝试在不移动指针的情况下从文件中读取时,您正在尝试从文件末尾读取。
您需要使用 seekg
移动到文件的开头以读取您编写的内容:
file << s;
cout << "ndata file contains :";
file.seekg(0);
while(getline(file, line))
{
cout << "n" << line;
}
我假设文件为空,在这种情况下,您可以执行以下操作
fstream file("TestFile.txt", ios::out);
cout << "enter your text :";
cin >> s; // Take the string from user
file << s; // Write that string in the file
file.close(); // Close the file
file.open("TestFile.txt",ios::in);
cout << "data file contains :" << endl;
while(getline(file, line)) { //Take the string from file to a variable
cout << line << endl; // display that variable
}
file.close();
cin.get();
正如其中一条评论所提到的...您也可以使用ifstream
和ofstream
进行更好的打磨