Home > front end >  C ofstream write in file from input, without new line after each word
C ofstream write in file from input, without new line after each word

Time:06-18

Basically I have a function, that writes into a .txt file. The user has to input, what will be written in the file. The problem is, every word has a new line, even tho it's written in the same line, while doing the input. But I want it to be the way the user inputs it.

    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();
}

Sample Input:

1st Input:Test Input

2st Input:Next input

Sample Output in file.txt:

Test

Input

Next

Input

(Without the spaces in between!)

CodePudding user response:

std::cin >> input; just reads to the first whitespace while std::getline(std::cin, input); would read the whole line.

One way of fixing it:

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';
}

I put the std::getline call last in the while condition to make the loop exit if std::getline fails.


Now, the above looks pretty nasty so I suggest putting clearing the screen and prompting the user in a separate function instead.

Example:

#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';
    }
}
  • Related