简体   繁体   English

扫描更多的值C

[英]Scanf more values C

i need help with short Code in C. I must read floats on input line seperated with space and input is ended with float 0 or EOF. 我需要C中短代码的帮助。我必须读取输入行上的浮点数,并用空格分隔,输入以浮点0或EOF结尾。

How to do this if i dont know how many numbers or in input, or how it works and ask to EOF if i am reading just numbers and not chars? 如果我不知道有多少个数字或输入内容,或者它是如何工作的,并问EOF如果我只读数字而不是字符,该怎么办?

Thanks for any response. 感谢您的任何回复。

example of input in one line: 一行输入示例:

12 11 10 45 50 12 EOF
12 10 11 45 0 

int main(void)  
{
    float num;
    float sum = 0;

    do{
       scanf("%f", num);
       sum += num;
    } while(EOF || num == 0);
    return 0;
}

From the man page of scanf - scanf的手册页中-

scanf returns the number of items successfully matched and assigned which can be fewer than provided for, or even zero in the event of an early matching failure. scanf返回成功匹配和分配的项目数,该数量可以少于提供的数量,如果早期匹配失败,则为零。 The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. 如果在第一次成功转换或匹配失败发生之前到达输入结束,则返回EOF值。

This means that scanf will return EOF only when it encounters EOF as the first input when it is called because EOF must be preceded with a newline '\\n' else it won't work (depending on the OS) . 这意味着scanf仅在被调用时遇到EOF作为第一个输入时才返回EOF,因为EOF必须以换行符'\\ n'开头,否则它将不起作用(取决于OS) You must also account for the matching failure scanf may encounter. 您还必须考虑scanf可能遇到的匹配失败。

#include <stdio.h>

int main(void) {
    float num;
    float sum = 0;
    int val;

    while((val = scanf("%f", &num)) != EOF && val == 1) {
        sum += num;
    }

    if(val == 0) {
        printf("matching failure. input is not a float.\n");
    }
    else {
        printf("end of input.\n");
    }

    return 0;
}

From scanf reference : scanf参考

On success, the function returns the number of items of the argument list successfully filled. 成功时,该函数返回已成功填充的参数列表的项目数。 This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file. 由于匹配失败,读取错误或文件结尾的范围,此计数可以与预期的项目数匹配或更少(甚至为零)。

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). 如果读取时发生读取错误或到达文件末尾,则会设置正确的指示符(低或错误)。 And, if either happens before any data could be successfully read, EOF is returned. 并且,如果在成功读取任何数据之前发生任何一种情况,则返回EOF。

If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ. 如果在解释宽字符时发生编码错误,则该函数将errno设置为EILSEQ。

So, you may rewrite your do-while loop to something like 因此,您可以将do-while循环重写为类似

int retval;
while((retval = scanf("%f", &num)) != EOF && retval > 0 && num != 0) {
    sum += num;
}

if(retval == 0) {
    printf("input read error.\n");
}

to match your constraints. 符合您的约束。

Also note you need to prefix your variable with & when passing it to scanf() , since the function expects a pointer to deal with (you need to pass variable address). 还要注意,将变量传递给scanf() ,需要在变量前加上&前缀,因为该函数需要处理指针(您需要传递变量地址)。

EDIT: 编辑:

see this topic concerning EOF problems in Windows 请参阅有关Windows中的EOF问题的主题

You can re write your code like this 您可以像这样重新编写代码

         int main(void) 
         {
            float num;
            float sum = 0;
            do
            {
               scanf("%f", &num);
               sum += num;
            } while((!feof(stdin)) && (num != 0));

            printf("%f", sum);
            return 0;   

          }

Here feof indicates end of input stream. feof表示输入流的结尾。

The following may be a slightly more robust way to do this: 以下是执行此操作的一种更可靠的方法:

#include <stdio.h>
#include <string.h>

int main(void) {
  int sum=0;
  int num;
  char *p;
  char buf[1000];
  fgets(buf, 1000, stdin);
  p = strtok(buf," ");
  while(p!=NULL) {
    if(sscanf(p, "%d", &num) == 1) sum+=num;
    p = strtok(NULL, " ");
  }
  printf("the sum is %d\n", sum);
}

Test: 测试:

> testme 
1 2 3 4 0

the sum is 10

> testme 
1 2 3 4 ^D
the sum is 10

Note - you have to enter ctrl-D twice to get the desired effect when you are at the end of a line. 注意-在行尾时,必须两次输入ctrl-D才能获得所需的效果。

you can get your doubt clear by reading "C programming a modern approach by KN King" 通过阅读“ KN King的C编程现代方法”,您可以消除疑问。

This book provides proper clarification on this topic 本书对此主题进行了适当的说明

Test the result of scanf() for 0 , 1 or EOF . 测试的结果scanf()01EOF
Test the value scanned for 0.0 . 测试扫描值0.0

int main(void) {
  float num;
  float sum = 0;
  int cnt;

  while ((cnt = scanf("%f", &num)) == 1) {
    if (num == 0.0) break;
    sum += num;
  }

  // cnt should be EOF, 0 or 1      

  if (cnt == 0) {
    printf("Input is not a number\n");
  }
  else {
    printf("Sum %f\n", sum);
  } 
  return 0;
}

Although, in general, scanf() returns values EOF, 0, 1, ... "number of format specifiers", a value of 0 occurs rarely. 尽管通常scanf()返回值EOF,0、1,...“格式说明符数”,但很少会出现值0。 Example input is "+". 输入示例为“ +”。

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

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