首页 > 解决方案 > 在流 c++ 的文本之前有一个额外的换行符

问题描述

我正在尝试将用户输入文本复制到文件中,并且它只是在文本开始之前添加换行符,如何让它不这样做?

    getline(cin, userInput);

    while (userInput != endWrite) {
        storyTime << userInput << endl;         
        getline(cin, userInput);
    }
    storyTime.close();

        return 0;
}

标签: c++ofstream

解决方案


您的代码不完整,因此不可能绝对确定会发生什么——乍一看,我的直接猜测是您所看到的可能是您未引用的某些代码的结果。对于一种明显的可能性,您可能会询问用户要在其中编写输出的文件的名称:

std::string outputName;

std::cout << "Enter output file name: ";
std::cin >> outputName;

std::ofstream storyTime(outputName);

//...

在这种情况下,std::cin >> outputName;读取文件名 - 但您必须按下enter键才能读取它,并且按下enter键将在输入中留下一个换行符,因此当您之后启动循环时,它'将被读取为用户之后输入的文本之前的换行符。

在旁边

除此之外,我通常会尝试使代码更简单一些:

while (std::getline(std::cin, userInput)) {
    storytime << userInput << '\n';
}

作为一个非常普遍的经验法则,我建议从文本文件中读取的格式化(使用 anystd::getline或 some operator>>)作为 an , 或其他的if条件while。习惯性地这样做可以更容易地编写正确处理文件的输入循环。

演示

只是为了它的价值,这里有一些不插入额外换行符的工作代码:

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

int main() {
    std::string userInput;

    std::string filename;
    std::cout << "Please enter file name: ";
    std::getline(std::cin, filename);

    std::ofstream output{filename};

    while (std::getline(std::cin, userInput)) {
        output << userInput << '\n';
    }
}

推荐阅读