我正在尝试将字符串输出到基本的 .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;
}
任何 future 的帮助将不胜感激 :) 提前致谢!
最佳答案
提取运算符截断空格。使用 std::getline()阅读整行。
代替:
cin >> mystring, "\n\n";
制作它:
std::getline( std::cin, mystring );
关于C++文件输出只接受第一个字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20456315/