这周我开始用 C++ 研究一个文本文件,在我的练习中我必须编写一个程序让用户在文件中输入行,但是......对于用户输入的每个空格,程序会询问新的给用户。
这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void){
ofstream myfile;
string answer;
do{
cout << "Insert a line in the file[END to finalize]: ";
cin >> answer;
myfile.open("example.txt");
myfile << answer;
myfile.close();
}while(answer != "END");
}
结果是:
Insert a line in the file[END to finalize]: Hello my friend
Insert a line in the file[END to finalize]: Insert a line in the file[END to finalize]: Insert a line in the file[END to finalize]:
最佳答案
operator>>(istream&, string&)
基本上捕获下一个词。如果你想捕获整行,试试std::getline(std::cin, answer);
.
getline
不过,不会包括换行符。这意味着你必须做类似 myfile << answer << '\n';
的事情将它们输出为行。
顺便说一句,在大多数情况下,您想要在循环外打开文件,或者打开它以附加类似 myfile.open("example.txt", ios::app);
的内容。 .每次都像你一样在循环中打开文件,我很确定你将文件指针放在文件的开头,所以你写的每一行都会至少覆盖前一行的第一部分。
关于c++ - 为什么 std::cin 字符串输入要求我输入每个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10708239/