user17499503
user17499503

Reputation:

How to get "\n" as an input and cout as new line

I want to get the string "hello \n world" as an input, and cout the \n in the string as a new line. When I write \n in the terminal, it can compile as a new line.

#include <iostream>
using namespace std;

int main(){
    string st;
    getline(cin, st);
    return 0;
}

Upvotes: 0

Views: 2110

Answers (1)

markovd
markovd

Reputation: 31

When you pass "\n" as a console input, it is considered as two separate characters - '\' and 'n'.

To achieve what you want, you will need to replace these two characters with new-line character manually.

You can achieve that like this:

#include <iostream>
#include <string>


int main(int argc, char** argv) {

    std::string line;
    std::getline(std::cin, line);

    // find the index where "\n" sequence starts
    const size_t index = line.find("\\n");
    // from there, replace two chars (size of the sequence) 
    // with new string - containing only '\n' character
    std::cout << line.replace(index, 2, "\n");

}

When executed, this will be the output (with first line being the input):

hello \n world
hello 
 world

This behavior can be simply generalized in creating a function, which takes string, sought sequence and replacing sequence as parameters and returns new string with replaced sequence. Something like:


std::string replace_sequence_in_with(const std::string& line, 
                                     const std::string& sequence, 
                                     const std::string& replaceWith) {
    const auto index = line.find(sequence);
    if (index == std::string::npos) {
        throw std::invalid_argument("Subsequence " + sequence + " not found.");
    }
    return line.replace(index, sequence.size(), replaceWith);
}

Upvotes: 3

Related Questions