[英]How to fix reading from file after using std::cin function
我的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;
}
輸出應為:
enter your text : alikamel // for example then write it to file data file contains : // file contents
但是我得到了這個:
enter your text : ass // for example and it write it to file then display data file contains : // nothing ??
為什么不顯示文件內容,怎么了?
您的問題是您試圖從文件末尾讀取。
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
以獲得更好的理解
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.