简体   繁体   中英

Removing blanks from an array using files

void read_input(FILE* inputfile,char array[]) {
     int nscan;
     char termch;
     while(TRUE) {
        nscan = fscanf(inputfile,"%30[^\n]%c",array,&termch);
        if (nscan == EOF)
          break;
        if (nscan != 2 || termch != '\n' ){
          printf("error  \n");
        }
     }
}

Here is my code, could please anyone help me find out why it shows the error message I've added, since the value of nscan is 2?

This:

if (nscan != 2 || termch != '\n' ){
  printf("error  \n");
}

says:

if nscan is not 2 print error. If termch is not a newline, print error. This is because you are using the OR logic operator, || . This explains the behavior you are getting.

So, if you want to see more, just print the values of both variables before reaching that if statement. For sure, termch will be something different than a newline.

remembering that on Windows and DOS, that the newline sequence is actually 2 characters and not just one...

remembering that the input line could be greater than 29 characters which would cause the second parameter to NOT contain the newline...

remembering that the input line could contain some white space like a space or tab, then the call to fscanf() will fail.

regarding these lines:

if (nscan != 2 || termch != '\n' ){
      printf("error  \n");
}

the 'if' condition is an or

And or means if either part is true, the result is true.

So when termch != '\\n' is true, then the enclosed function body will be executed.

Suggest modify that 'if' statement to:

if (nscan != 2 ) 
{
    printf( "fscanf failed to read both parameters\n");
}
else if(termch != '\n' ) 
{
    printf( "fscanf failed to read the complete line\n");
}

such that meaningful messages are output.


Also, the while() loop and enclosed code leaves a bit to be desired.

suggest:

while(1)
{
    if( 1 != (nscan == fscanf(inputfile,"%30[^\n]\n",array) ) )       
    { 
        perror( "fscanf failed to read full line of input" );
    }
}

of course, if the input line is greater than 29 characters then the error message will be output and the next iteration of the loop will read the rest of the line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM