[英]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.