简体   繁体   English

使用文件从阵列中删除空白

[英]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? 这是我的代码,由于nscan值为2,请问有谁能帮助我找出为什么显示我添加的error消息?

This: 这个:

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

says: 说:

if nscan is not 2 print error. 如果nscan不是2打印错误。 If termch is not a newline, print error. 如果termch不是换行符,则打印错误。 This is because you are using the OR logic operator, || 这是因为您正在使用OR逻辑运算符|| . 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. 因此,如果要查看更多内容,只需在到达该if语句之前打印两个变量的值即可。 For sure, termch will be something different than a newline. 当然, termch与换行符有所不同。

remembering that on Windows and DOS, that the newline sequence is actually 2 characters and not just one... 记住在Windows和DOS上,换行符实际上是2个字符,而不仅仅是一个字符...

remembering that the input line could be greater than 29 characters which would cause the second parameter to NOT contain the newline... 记住输入行可能大于29个字符,这将导致第二个参数不包含换行符...

remembering that the input line could contain some white space like a space or tab, then the call to fscanf() will fail. 记住输入行可能包含一些white space例如空格或制表符,那么对fscanf()的调用将失败。

regarding these lines: 关于这些行:

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

the 'if' condition is an or 如果条件为or

And or means if either part is true, the result is true. or表示如果任一部分为真,则结果为真。

So when termch != '\\n' is true, then the enclosed function body will be executed. 因此,当termch!='\\ n'为true时,将执行封闭的函数体。

Suggest modify that 'if' statement to: 建议将“ if”语句修改为:

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. 而且,while()循环和封闭的代码还有一点不足。

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. 当然,如果输入行大于29个字符,则将输出错误消息,并且循环的下一次迭代将读取行的其余部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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