如何在不转换为字符串的情况下一次传递多个整数

How to pass many integers one at a time without converting to string

我可以要求用户输入并将其插入到链表中。所以下面将从用户那里得到 1 个整数:

  printf("Enter an integer: ");
  scanf("%d",&value);
  insert(value); // insert value to linked list

但我希望用户能够输入许多整数(想输入多少就输入多少)。示例:Enter an integer: 5 6 7 8 9 并将 5 添加到 insert 然后,将 6 添加到 insert 等等。

我读了这个 post“reading two integers in one line using C#”,建议的答案是使用字符串数组,但我不想那样做。我希望用户输入的每个数字都输入到链表中。

主要功能:

int main(){
   printf("Enter integer(s) : ");
   scanf("%d",&num);
   insert(num);
   return 0;
}

谢谢

一种方法是首先扫描一个整数以确定要读取的整数数量,然后读取那么多整数并将它们存储到您的列表中。

int i, size;
int x;
scanf("%d", &size);
for(i=0; i < size; i++){
    scanf("%d", &x);
    insert(x);
}

示例输入如下:

4
10 99 44 21

您可以在 scanf 中使用格式化程序,它会在用户点击回车时获取所有内容

char array[256];
scanf("%[^\n]",array)

然后使用

int num;
while(*array !='[=11=]') // while content on array is not equal to end of string
{
  if(isspace(*array)) // need to check because sometimes when atoi is  returned, 
                         // we will move only one location size of char,
                         //and convert blank space into integer
   *array++;

else{
   num=atoi(*array);   // function atoi transform everything to blank space
   insert(num);
   *array++;   // then move to the next location in array

 }
}

你为什么不为此添加一个简单的while/for循环

printf("total numbers to input? ");
scanf("%d",&i);
printf("\nEnter integer(s) : ");
while(i--){
   scanf("%d",&num);
   insert(num);
}