【问题标题】:How to pass many integers one at a time without converting to string如何一次传递多个整数而不转换为字符串
【发布时间】:2015-04-18 17:04:57
【问题描述】:

我可以向用户询问输入并将其插入到链接列表中。所以下面会从用户那里得到 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 等等。

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

主要功能:

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

谢谢

【问题讨论】:

  • 您可以在printfscanfinsert 循环上循环固定次数,或者直到用户在完成后输入其他内容。这取决于您更具体的需求。

标签: c arrays string linked-list integer


【解决方案1】:

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

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

然后使用

int num;
while(*array !='\0') // 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

 }
}

【讨论】:

  • 注意:使用scanf("%[^\n]",array),如果用户输入"\n",则不会将任何内容读入array,它保持未定义,"\n" 保持在stdin
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    输入示例如下:

    4
    10 99 44 21
    

    【讨论】:

    • 太棒了,没想到:)
    • "4 10 99 44 21" 的用户输入将得到与 "4 10" 相同的响应 "99 44 21"。没有检测到行尾。
    • @chux 是的,这是正确的。此外,首先将所有整数扫描到长度为size 的数组中,循环遍历数组,同时插入每个元素,最后释放内存可能会更安全。
    • @chux 是的,你是对的,我们该如何解决这个问题?
    • @Dave scanf() 很难用于读取用户输入的 。大多数格式说明符将空格和'\n' 同等对待,因此 line 与空格分隔符的概念丢失了。最好使用fgets()getline() (*nix) 阅读,然后使用sccanf()strtol() 等解析/扫描该行。关于此的SO 帖子有数百个. (尝试搜索[c] scanf vs fget
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 2020-01-25
    相关资源
    最近更新 更多