getline function

hello, how do I use the getline function to count the number of characters (like the plus sign, minus sign, etc) in a txt file?

would the following code be correct?

1
2
3
4
5
6
7
8
9
string line;
int num = 0;
int plussign = 0;
while (getline(inputFile, line))
{
    num++; // counts number of lines
    if (line == "+") 
        plusign++;
}   
That will count the number of lines in your file. And it will count the number of times each line contains only the string "+".

try this...
1
2
while ( getline( inputFile, line, "+" ) )
  plusign++;
What do you think that will accomplish?
avhishekm71, I tried it but the getline function can't accept a third parameter.

@jlb, so how do I count the number of plus signs in a line?

I know how to do it using the .get

like
1
2
3
4
5
6
 
line =  inputFile.get();
if (line == "+")
{
plussign++;
}


Just a lil confused on this. Thanks for your replies.
Kiwihead wrote:
I tried it but the getline function can't accept a third parameter.

The third parameter is of type char.
http://www.cplusplus.com/reference/string/string/getline/
Last edited on
@Kiwihead

Here's a way to count different items in the string. Add whatever else you're wanting to check for, in the for loop.


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
// Check line.cpp : main project file.

#include <string>
#include <iostream>

using namespace std;

int main()
{
	string line;
	int num;
	int plussign = 0, negsign=0, commasign=0, periodsign;
	do
	{
		plussign = 0, negsign=0, commasign=0, periodsign = 0; // Zero out the variables
		cout << "enter a line with '+', '-', '.' and ',' in it" << endl;
		getline(cin,line);

		num = line.length();
		for(int x=0;x<num;x++)
		{
			if (line[x] == '+')
				plussign++;
			if (line[x] == '-')
				negsign++;
			if (line[x] == ',')
				commasign++;
			if (line[x] == '.')
				periodsign++;
		}
		if( num >0) // Print out line only if something was entered
			cout << "You had " << plussign << " plus signs, " << negsign << " minus signs, " << periodsign << " periods and " << commasign << " commas.." << endl << endl; 
	} while (num > 0);
}
Thanks a lot <3
Topic archived. No new replies allowed.