A.be
A.be

Reputation: 61

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

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?

Upvotes: 6

Views: 27325

Answers (2)

praisethemoon
praisethemoon

Reputation: 86

I would like to start by defining what a new line is. On windows, it is a sequence of two characters \r\n, on UNIX it is simply \n. Treating new line as '\n' will suffice in your case since your dealing with text input (not binary, as C will handle the translation).

I suggest you split your problem into two sub-problems:

  1. Store one line
  2. Iterate while there are more lines

I would do something like this:

#include <iostream>
#include <cstring>
using namespace std;

char* nextLine(char* input, int* pos) {
  char* temp = new char[200];
  int lpos = 0; // local pos

  while(input[*pos] != '\n') {
    temp[lpos++] = input[(*pos)++];
  }

  temp[*pos] = '\0';

  (*pos)++;

  return temp;
}

int main() {
    char str[] = "hello\nworld!\ntrue";
    int pos = 0;

    while(pos < strlen(str)){
        cout << nextLine(str, &pos) << "\n";
    }

    return 0;
}

Hope that helps!

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

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.

Upvotes: 4

Related Questions