用scanf读取int直到换行 [英] read int with scanf until new line
问题描述
我是C语言的新手,以前使用过Java,所以我对某些东西不太熟悉...我想读取一个不确定数量的整数,直到出现新的一行为止.我知道,新行是⁄n并且我已经有一个代码,因此将读取整数,直到您键入字母为止,但是如果有新行,它不会停止.
I'm new to the c language and used java before, so I'm not so familiar with some things... I want to read an indefinite number of integer until there's a new line. I know, that new line is ⁄n and I already have a code, so the integer are read until you type in a letter, but it doesn't stop, if there's a new line.
#include <stdio.h>
int main() {
int i, numberOfNumbs=0,total=0,value, valsRead;
float average;
valsRead = scanf("%d",&value);
while(valsRead>0)
{
numberOfNumbs++;
total +=value;
printf("Read %d\n", value);
valsRead = scanf("%d",&value);
}
average=(float)total/(float)numberOfNumbs;
printf("You read %d values. Average = %f.",numberOfNumbs, average);
return (0);
}
输入应该是这样的:23 4 114 2 34 3224 3 2 ⁄n
The input should be something like this: 23 4 114 2 34 3224 3 2 ⁄n
预先感谢
推荐答案
scanf
不是行为设计.它适用于以空格分隔的输入,其中空格是空格,制表符,\ r或\ n的任意组合.
scanf
is not line oriented by design. It is aimed for blank separated inputs, where blanks are any combinations of spaces, tabs, \r or \n.
如果要使用面向行的输入,则应使用 fgets
在字符串中获取一行,然后使用strtok和sscanf来解析该字符串.您的代码可能会变成:
If you want to use line oriented input, you should use fgets
to get a line in a string and then strtok and sscanf to parse the string. Your code could become :
#include <stdio.h>
#include <string.h>
/* maximum size of an input line : adapt to your needs */
#define SIZE 256
int main() {
int i, numberOfNumbs=0,total=0,value, valsRead;
float average;
char line[SIZE], *val;
char delims[] = " \t\r\n";
if (fgets(line, SIZE, stdin) == NULL) { /* EOF */
fprintf(stderr, "No input\n");
return 1;
}
if (line[strlen(line) - 2] != '\n') {/* line too long */
fprintf(stderr, "Line too long\n");
return 2;
}
val = strtok(line, delims);
valsRead = sscanf(val, "%d",&value);
while(valsRead>0)
{
numberOfNumbs++;
total +=value;
printf("Read %d\n", value);
val = strtok(NULL, delims);
valsRead = (val == NULL) ? 0 : sscanf(val, "%d",&value);
}
average=(float)total/(float)numberOfNumbs;
printf("You read %d values. Average = %f.",numberOfNumbs, average);
return (0);
}
这篇关于用scanf读取int直到换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!