Home > Back-end >  My if statement is not working while reading file
My if statement is not working while reading file

Time:10-18

In this code I dont know why but if (temp == '\n') is not working, therefore in output there is all zeros and that zeros in ith index doesnt update

while(fin.eof() != 1)
{
    if(temp ==  '\n' ) 
    {
        k = 0;
        j = 0;
        i  ;
        cout << "call from 2nd if";     
    }
    if(temp == ',')
    {
        k = 0;
        j  ;
        cout << "call from 1st if";
    }
    fin >> temp; 
    data[i][j][k] = temp;
    
    cout << "address " << i << j << k << " : " << data[i][j][k] << endl;
    k  ;
    i,j;
}

OUTPUT:

   address at **0**31 : u
   address at **0**32 : i
   address at **0**33 : c
   address at **0**34 : e
   address at **0**35 : B
   .
   .
   .

basically it is 3dimesnional array where i th value is not updating ,what is solution to this

CodePudding user response:

if(temp == '\n' ) replace with if(isspace(temp)).

CodePudding user response:

It is a very bad idea to loop on eof in C . If your file is empty, fin.eof() will be false until you try to read something from it.

So as a first corrective measure change to:

while(fin >> temp)
{
    ....
} 

We then assume that temp is defined as char, because you read char by char.

The trouble is that >> tends to swallow a lot of spaces, including ' ' and '\n' that you'll never get. If you do expect to get some white, you need to set std::noskipws:

while(fin >> noskipws >> temp)
{
    ....
} 

But if you're reading char by char, a better approach could be to read with fin.get()

  • Related