简体   繁体   English

C ++文件输出仅接受第一个单词

[英]C++ file output only accepts the first word

I'm trying to output a string to a basic .txt file. 我正在尝试将字符串输出到基本的.txt文件。 And it only partially works, and by that I mean that it only accepts the first word of whatever I type. 而且它仅部分起作用,并且我的意思是说它只接受我键入的所有内容的第一个单词。 I need to be able to have no character limit as well (the user can type in however much they want) 我还需要没有字符数限制(用户可以输入任意数量的文字)

#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;

}

Any future help will be greatly appreciated :) Thanks in advance! 任何未来的帮助将不胜感激:)预先感谢!

The extraction operator truncates on whitespaces. 提取运算符在空白处截断。 Use std::getline() to read the entire line. 使用std :: getline()读取整行。

Instead of: 代替:

cin >> mystring, "\n\n";

Make it: 做了:

std::getline( std::cin, mystring );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM