Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a newline in string input in C++

Tags:

I want to count each newline
If the input like this:

Hi moon
this day I wanna
help

Should be the output like this:

1 Hi moon
2 this day I wanna
3 help

I write this code:

int main() {
    string str; int c = 0;
    cin >> str;
    int j = 0;
    string t[200];
    while (str != ";")
    {
        t[j] = str;
        cin >> str;

    }
    for (int i = 0; i < j;i++){
    cout << c << " " << t[j];

    if (t[j] == "\n") c++;
}

    system("Pause");
    return 0;
}


and I was to try :

int c[100];
    cin >> str;
    int j = 0;
    string t[200];
    while (str != ";")
    {
        string temp;
        t[j] = str;
        temp = t[j];
        if (temp.find("\n"))
            c[j] += 1;
        cin >> str;

    }
    for (int i = 0; i < j;i++){
    cout << c[i] << " " << t[j];

}

Can anyone tell to me how to detect a newline in string input and print it?

like image 721
A.be Avatar asked Apr 11 '17 09:04

A.be


People also ask

Can scanf detect newline?

We can make scanf() to read a new line by using an extra \n, i.e., scanf(“%d\n”, &x) . In fact scanf(“%d “, &x) also works (Note the extra space). We can add a getchar() after scanf() to read an extra newline.

How do you check if a character is a newline?

Simply comparing to '\n' should solve your problem; depending on what you consider to be a newline character, you might also want to check for '\r' (carriage return).

Is \n considered a string?

On the other hand (as Paul Griffiths' answer points out), "\n" (with double quotes rather than single quotes) is a string literal that represents a string value. That string consists of two characters, a single '\n' newline character and a '\0' null character that marks the end of the string.


1 Answers

Use std::getline to read line by line. Put in a std::vector. Print the vector indexes (plus one) and the strings from the vector.

like image 82
Some programmer dude Avatar answered Sep 25 '22 09:09

Some programmer dude