Nitin Bansal Nitin Bansal - 2 months ago 6
C++ Question

Output while File Reading not as Expected in C++

I am trying to read a file, and whenever I find a '#' I would not print that line on stdout; For doing that I am taking a simple approach, where I check the 1st character of each line and if it is #, then skip.. But when I am trying to print # for each line where # is present I am not able to:

Code:




if (f.is_open())
{
while(getline(f,str, ' '))
{
cout <<str<<endl;
cout << str[0]<<endl;





***File Opened contains:
P5
####My name is Nitin Bansal***

Output:

P5
####My
P
name
n
is
i
Nitin


As you see, I expected that I would get P in nextline after P5 but no .. I get it after ####My, and I dont get # after ###My ...?????

Answer

Simply remove the last argument of getline() and it works

while (getline(f, str))
{
    cout << str << endl;
    cout << str[0] << endl;
    if (str[0] == '#') // do your stuff when first char is '#'
}

See it working here.

EDIT

Since you're wondering why there's no '#', it's simple: The way you're using getline, it will stop only on whitespaces (' '). So it will read "P5\n####My" as a line. Thus, it'll print 'P' after, but no '#'.

Comments