【发布时间】:2014-06-24 22:15:40
【问题描述】:
我知道我可以使用
scanf("%d %d %d",&a,&b,&c):
但是如果用户首先确定一行中有多少输入呢?
【问题讨论】:
-
只使用一个循环。
我知道我可以使用
scanf("%d %d %d",&a,&b,&c):
但是如果用户首先确定一行中有多少输入呢?
【问题讨论】:
您正在读取输入的数量,然后重复(循环)读取每个输入,例如:
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av)
{
int numInputs;
int *input;
printf("Total number of inputs: ");
scanf("%d", &numInputs);
input = malloc(numInputs * sizeof(int));
for (int i=0; i < numInputs; i++)
{
printf("Input #%d: ", i+1);
scanf("%d", &input[i]);
}
// Do Stuff, for example print them:
for (int i=0; i < numInputs; i++)
{
printf("Input #%d = %d\n", i+1, input[i]);
}
free(input);
}
【讨论】:
读入整行,然后使用循环解析出你需要的内容。
让您开始:
1) 这是 getline(3) 的手册页: http://man7.org/linux/man-pages/man3/getline.3.html
2) getline 的一些替代方案: How to read a line from the console in C?
3) 考虑压缩空格: How do I replace multiple spaces with a single space?
4) 使用循环进行解析。您可能会考虑标记化: Tokenizing strings in C
5) 请注意,您的用户可以输入任何内容。
【讨论】:
#include <conio.h>
#include <stdio.h>
main()
{
int a[100],i,n_input,inputs;
printf("Enter the number of inputs");
scanf("%d",&n_input);
for(i=0;i<n_input;i++)
{
printf("Input #%d: ",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n_input;i++)
{
printf("\nInput #%d: %d ",i+1,a[i]);
}
}
【讨论】: