[英]Writing to txt file C++
我想在文件中寫入單詞,直到我輸入單詞“stop”,但只有第一個單詞被保存到文件中。 有什么問題?
int main(int i)
{
ofstream file;
string file_name,message;
cout << "\nFilename: ";
cin >> file_name;
cout << "Write 'stop' to end writig to file" << endl;
for(i=0; message!="stop"; i++)
{
cout << "\nYour message: ";
cin >> message;
file.open(file_name.c_str());
file << message.c_str() << "\t" ;
}
file.close();
return 0;
}
它應該是,
int main()
{
int i;
ofstream file;
string file_name,message;
cout << "\nFilename: ";
cin >> file_name;
cout << "Write 'stop' to end writig to file" << endl;
file.open(file_name.c_str());
for(i=0; message!="stop"; i++)
{
cout << "\nYour message: ";
cin >> message;
if(message == "stop"){ //If you dont want word stop
break;
}
file << message.c_str() << "\t" ;
}
file.close();
return 0;
}
如果你做類似的事情會更好,
do{
//do stuff
if (message == "stop")
break;
}while(message != "stop");
在這種情況下,您最好切換到以下形式的 while 循環: while (.file.eof())
或while (file.good())
。
除此之外,for循環必須定義變量,在你的情況下,我是未定義的,並且必須包含變量的范圍並且沒有其他變量定義(消息的條件不能在其中。它必須是一個if條件在for循環內)。
...
char word[20]; // creates the buffer in which cin writes
while (file.good() ) {
cin >> word;
if (word == "stop") {
break;
...
}
}
...
實際上,在您的情況下,我完全不確定它是如何編譯的:) 供將來參考: for循環應如下所示: for (int i = 0; i<100; i++) {};
我希望這很清楚!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.