我正在尝试将字符串输出到基本.txt文件。它只是部分起作用,我的意思是它只接受我输入的任何内容的第一个单词。我需要能够没有字符限制(用户可以输入他们想要的更多)
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream in_stream;
ofstream out_stream;
in_stream.open("advice.txt");
if (in_stream.fail())
{
cout << "input file opening failed.\n";
exit(1);
}
char next;
in_stream.get(next);
while (! in_stream.eof())
{
cout << next;
in_stream.get(next);
}
out_stream.open("advice.txt", ios::app); //Append data to file
if (out_stream.fail())
{
cout << "output file opening failed.\n";
exit(1);
}
//Output text into the file (Problem is in here)
string mystring;
cin >> mystring, "\n\n";
out_stream << " - " << mystring << "\n\n";
in_stream.close();
out_stream.close();
cin.get();
cin.get();
return 0;
}
任何未来的帮助将不胜感激:)提前致谢!
答案 0 :(得分:5)
提取运算符在空格上截断。使用std::getline()读取整行。
而不是:
cin >> mystring, "\n\n";
成功:
std::getline( std::cin, mystring );