c++ - 写入文件时不能使用 getline?

标签 c++

我正在尝试将由 cin 命令设置的字符串写入文件。我让它工作,但它并没有写出所有的字符串;只是第一个空白之前的所有内容。所以有人建议我使用:

Write_Test << getline( Text , cin );

让它接受空格,但正如标题所说我不能使用 getline?

所有代码:

string Text;
        cout << "Write something: ";
        cin >> Text;
        if (Text != "")
        {           
            ifstream Write_Test("Write_Test.txt");//Creating the file       
            //Write_Test << Text;       //Write a message to the file.
            Write_Test << getline( Text , cin );
            Write_Test.close();                 //Close the stream, meaning the file will be saved.     
            cout << "Done!";
        }

感谢您的帮助!

最佳答案

首先,你可能打算写

std::getline(std::cin, Text)

此表达式采用 std::istream& 并返回此 std::istream&。假设你得到了 getline() 的参数,表达式

out << std::getline(std::cin, Text)

实际上是将std::cin的流状态写入out。这可能是您想要的,但我猜您实际上是想使用

if (std::getline(std::cin, Text)) {
    WriteTest << Text;
}

这应该将从 std::cin 读取的一行文本写入 WriteTest

一个完整的程序看起来像这样:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

int main()
{
    std::ofstream out("WriteTest.txt");
    if (!out) {
        std::cout << "Error: failed to open output file\n";
        return EXIT_FAILURE;
    }
    std::string text;
    if (std::getline(std::cin, text)) {
        out << text << '\n';
    }
    else {
        std::cout << "Error: failed to read a line\n";
}

关于c++ - 写入文件时不能使用 getline?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18923051/

相关文章:

c++ - std::ostream 的浮点格式

c++ - 使用 STL 在 C++ 中计算分区

c++ - 如何在 C++11 的函数内初始化线程安全的静态常量 vector ?

c++ - 在 ITK 中使用 DemonsRegistrationFilter 的困难

c++ - VC++ 2015 没有链接,但 VC++ 2012 有

c++ - 无法使用比较器初始化 std::function

C++ 结构模板特化

c++ - 如何创建 COM DLL(类库)?

c++ - C++ 程序终止时的内存返回

c++ - 为什么在 sqlite - QT here - 中触发查询失败?