C++文件输出只接受第一个字

标签 c++ string file file-io fstream

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

相关文章:

c++ - 读取 iostream 直到找到字符串定界符

Android 3.x+ Java ZipFile 类 - 无法从大文件中读取 ZipEntries

c - 从 C 文件中读取二维数组

java - 编辑外部存储中的文件

c++ - 将值存储在链表的结构中

c++ - 迭代创建变量

c++ - STL中关联数组(map)的速度

string - scala string.split 不起作用

c# - 如何在不使用 ToString() 的情况下在 C# 中将 Int 转换为 String?

c - 128 位类型错误