2015-02-17 62 views
3

我能够向用户询问输入并将其插入链接列表。所以下面将得到1个整数从用户:如何一次传递多个整数而不转换为字符串

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

但我想用户能够输入许多整数(他们想要的数量)。例如:Enter an integer: 5 6 7 8 9并加5insert然后,加6insert等等。

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

主要功能:

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

感谢你这样做

+4

你可能只是在你的'printf','scanf','insert'周期为一个固定的次数循环,或直到用户输入别的东西的时候完成的。这取决于你的更具体的需求。 – lurker 2015-02-17 21:06:37

回答

4

一种方法是先扫描一个整数来标识整数的数读入,然后读取许多整数和存储他们进入你的名单。

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

例输入将是这样:

4 
10 99 44 21 
+0

伟大的,从来没有想到:) – 2015-02-17 21:27:56

+0

''4 10 99 44 21“'的用户输入将得到相同的响应以及'”4 10“''”99 44 21“'。没有检测到结束行。 – chux 2015-02-17 21:33:23

+0

@chux是的,这是正确的。另外,首先将所有整数扫描到长度为size的数组中,然后循环遍历数组,并行插入每个元素并最终释放内存可能更安全。 – SovMoose 2015-02-17 21:36:00

1

您可以使用格式在scanf其中由时间用户点击进入

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 

} 
} 
+0

注意:用'scanf(“%[^ \ n]”,array)',如果用户输入'“\ n”',它仍然是未定义的,'\ n“'仍然保留在'stdin'中。 – chux 2015-02-17 21:30:41

1

为什么你不是一个DD简单while/for循环这个

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