【问题标题】:C++ file output only accepts the first wordC++ 文件输出只接受第一个单词
【发布时间】:2013-12-25 17:13:34
【问题描述】:

我正在尝试将字符串输出到基本的 .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;

}

我们将不胜感激任何未来的帮助 :) 提前致谢!

【问题讨论】:

    标签: c++ string file file-io fstream


    【解决方案1】:

    提取运算符会截断空格。使用std::getline() 读取整行。

    代替:

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

    制作:

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

    【讨论】:

    • 参考我的代码,我到底应该把它放在哪里?它会取代我的 cin 声明吗?我在哪里引用我的 out_stream?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 2014-08-03
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多