data file handling program

How to write a program to count and display the number of lines ending with 'n' or 'N' in a text file?
Last edited on
1) Read the text from the file
2) Iterate over each line in the file
3) Check whether the line ends in an 'n' or 'N'
4) If it does, increment a counter.
How to check whether the end of line contains 'n' OR 'N'?
What have you tried?
If you read each line as a std::string, the back() function can be used to access the last character. (provided the line is not empty).

http://www.cplusplus.com/reference/string/string/back/

Though if you need to ignore trailing spaces, a different idea may be needed.
Last edited on
@jlb Honestly I cant figure out any way to do this.
My teacher though had told me about taking the line as string and using strlen function to count the number of characters and then compare the last character with 'n' or 'N' and increment "count(variable that stores the number of lines)" if its is equal to 'n' or 'N'.

But my problem is how to read the last character of a line?
Here is how to read the last character of a string.
char last_character = theString.back();


Here is how to read a line from an input file into a string:
ifstream_object >> theString;


Now you join up these thoughts.
Last edited on
My teacher though had told me about taking the line as string and using strlen function to count the number of characters
strlen() is used with c-strings (an array of characters). That would be used if you were writing C code.

Perhaps we are talking at cross purposes, the earlier comments were regarding C++ std::string.

Are you asking about a C or C++ solution? For example, how do you open and read the file?

In C++ you could follow the second example under the heading Text files in the tutorial here:
http://www.cplusplus.com/doc/tutorial/files/

I know how to open and read from file, the only problem I have is how to get the last character of a line from a text file.
the only problem I have is how to get the last character of a line from a text file

Well, your teacher suggested a C solution, people here have suggested a C++ solution.

So what remains to be solved now?

this error comes up when I use the back() function 'std::string' has no member named 'back'
Thanks for the reply. Perhaps your compiler is older and does not support the latest features (c++11 standard) or is not configured to do so.

As an alternative, first get the string size:
http://www.cplusplus.com/reference/string/string/size/

Check that the string is not empty (size is not zero)
and then the subscript of the last character is just size-1

To access any character using its subscript, use either array notation []:
http://www.cplusplus.com/reference/string/string/operator%5B%5D/
or the at() function
http://www.cplusplus.com/reference/string/string/at/

thanx a lot :)
worked like charm.
Topic archived. No new replies allowed.