Getting '\n' out of a variable string

Hi all,

I'm trying to check if a string contains a \n character and then incrementing an int to get to know the currentlinenumber.

This is what I've got so far:

1
2
3
4
5
6
7
8
9
     
for(int i = 0; i<input.size();i++)
     {
      if(strcmp(input.at(i),"\n",2)==0)
      {
         LineNumber++;
         cout << "this input has: "<<LineNumber<<" linenumbers";
      }
     }


Where input is a variable string gotten from cin >> input.

This code gives me an error because, the char I get from input.at(i) cannot be converted from a char to a const char*.

Anyone know the answer?

Thanks in advance

P.S. Off course I created input and LineNumber already so don't worry about that.
Don't use strcmp, use the comparison operator, and single quotes around the newline character.
 
input.at(i) == '\n'

ropez is correct. The reason is that strcmp is used to compare two arrays of characters (or C-strings), but the .at() function returns a character.
closed account (z05DSL3A)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <string>
#include <algorithm>

int main(int argc, char *argv[])
{
    std::string str("this\nis\na\ntest\n");
    int count =0;

    //method one

    for(int i = 0; i < str.size(); i++)
    {
        if (str.at(i) == '\n')
            ++count;
    }
    cout << count << endl;

    //method two
    count = 0;

    for (std::string::iterator itr = str.begin(); itr != str.end(); ++itr)
    {
        if (*itr == '\n')
           ++count;
    }
    cout << count << endl;

    // method three
    count = (int) std::count(str.begin(), str.end(), '\n');
    cout << count << endl;

    return 0;
}
Topic archived. No new replies allowed.