如何从单个任意长的格式化(例如空格分隔)键盘行填充 double 或整型数组?
例如:
Enter the elements of the array:
2 32 12.2 4 5 ...
应该导致
=> array[0] = 2
=> array[1] = 32 etc.
我知道我可以按如下方式使用 scanf,但这并不能解决我的问题,因为每个元素都应该一一输入。
/* Input data from keyboard into array */
for (count = 1; count < 13; count++)
{
printf("Enter element : %d: ", count);
scanf("%f", &array[count]);
}
谢谢。
最佳答案
I know that I can use scanf as follows, but that does not solve my problem, since each element should be entered one by one.
没有。如果您不使用换行符,那将完全没问题。
一般来说,避免使用 scanf()
是个好主意,尽管它不是使用起来最直观的函数(可以这么说)。如何使用 fgets()
读取行,然后使用 strtof()
解析它?
char buf[LINE_MAX];
fgets(buf, sizeof buf, stdin);
char *s = buf, *endp;
int i = 0;
for (i = 0; i < 13; i++) {
array[i] = strtof(s, &endp);
s = endp;
}
关于c - 从 C 中的单个格式化键盘行填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18751359/