繁体   English   中英

C++ ofstream 从输入写入文件,每个单词后没有换行符

[英]C++ ofstream write in file from input, without new line after each word

基本上我有一个 function,它写入一个.txt文件。 用户必须输入写入文件的内容 问题是,在进行输入时,每个单词都有一个新行,即使它写在同一行中。 但我希望它是用户输入它的方式。

    void Log_Write::WriteInLog(std::string LogFileName)
{
    system("cls");
    std::string input;
    std::ofstream out;
    out.open(LogFileName, std::fstream::app);
    out << "\n\nNEW LOG ENTRY: " << getCurrentTime()<<"\n"; // 
    while (true)
    {
        system("cls");
        std::cout << "Writing in Log\n\nType 'x' to leave editor!\n\nInsert new entry: ";
        std::cin >> input;
        if (input == "x")
            break;
        out << input << "\n"; // How do I change this so it doesn't create a new line for each word
    }
    out.close();
}

示例输入:

第一个输入:测试输入

第二个输入:下一个输入

file.txt 中的示例 Output:

测试

输入

下一个

输入

(中间没有空格!)

std::cin >> input; std::getline(std::cin, input); 会读整行。

一种修复方法:

while(
    system("cls"),
    std::cout << "Writing in Log\n\nType 'x' to leave editor!\n\nInsert new entry: ",
    std::getline(std::cin, input)
) {
    if (input == "x")
        break;
    out << input << '\n';
}

我将std::getline调用放在while条件的最后,以便在std::getline失败时退出循环。


现在,上面看起来很讨厌,所以我建议将清除屏幕并在单独的 function 中提示用户。

例子:

#include <iostream>
#include <string>
#include <string_view>

std::istream& prompt(std::string_view prompt_text, std::string& line,
                     std::istream& in = std::cin,
                     std::ostream& out = std::cout) {
    std::system("cls");
    out << prompt_text;
    std::getline(in, line);
    return in;
}

void Log_Write::WriteInLog(std::string LogFileName) {
    // ...

    auto prompt_text = "Writing in Log\n\n"
                       "Type 'x' to leave editor!\n\n"
                       "Insert new entry: ";
    
    while (prompt(prompt_text, input)) {
        if (input == "x") break;
        out << input << '\n';
    }
}

暂无
暂无

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

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