c++ - 写入txt文件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;
}
解决方案
在这种情况下,您最好切换到形式为:while (!file.eof())
或的 while 循环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++) {};
我希望这很清楚!
推荐阅读
- html - 像 pinterest 这样的网格布局仅使用 css 而没有 javascript
- css - 更改 CSS 边框速记语法顺序可以吗?
- python - 将两列csv文件数据转换成字典
- php - 在 Codeigniter 中修改时编辑日期
- python - 如何在python中导入本地类
- sql - SnowSQL - 验证 -
- python - 与单个列相比,在数据帧中一次去除空格的优雅方法
- android - 如何在网格布局中获取行和列值?
- android - 在新的 Google 地点选择器中找不到样式/PlacesAutocompleteThemeOverlay
- assembly - x86 / x64 使用相对跳转从子程序返回