2

I know C++ but I am trying to write my first C program and I'd like to be able to get one line of input from a user and convert it to 10 different numbers. For example, a user will be prompted to enter some numbers and they will enter up to 10 numbers:

Input up to 10 numbers:

> 34412 12455 435234 44 199 4735890 034001 154595

Then I'd like to store them an in array and do stuff with them later. I've searched for how to get input but most of what I've found isn't clear to me. Any help would be appreciated, thanks!

4

3 回答 3

2

如果您确定用户总是输入由空格/制表符和换行符分隔的整数,并且不超过 10 个,您可以使用这一行来解决问题:

int arr[10];
int count = 0;

while(scanf("%d",&(arr[count++])))
   ;

它利用了scanf返回匹配项的数量这一事实。

于 2013-02-03T00:22:54.143 回答
1

您可以从用户输入中读取行,对其进行标记,然后使用以下方法直接从标记中检索数字 sscanf

// array big enough to hold 10 numbers:
int numbers[10] = {0};

// read line from users input:
char inputString[200];
fgets(inputString, 200, stdin);

// split input string into tokens:
char *token = strtok(inputString, " ");

// retrieve a number from each token:
int i = 0;
while (token != NULL && i < 10) {
    if (sscanf(token, "%d", &numbers[i++]) != 1)
        ; // TODO: ERROR: number hasn't been retrieved
    token = strtok(NULL, " ");
}
于 2013-02-03T00:21:25.130 回答
1

您需要阅读一些关于 C 函数的内容:

  1. fgets()读取整行。删除末尾的换行符。
  2. strtok()对行进行标记。
  3. strtol()将每个字符串转换为整数。
  4. 将它们存储在一个数组中。

如果您不担心无效输入,可以使用sscanf()从 C 字符串中读取。

于 2013-02-03T00:06:10.483 回答