[英]Putting users input consisting of numbers separated by commas into an array?
我正在从用户那里输入10个数字(用户在提示符下输入它们,并且数字之间用逗号分隔,例如:245645,-243、4245)。 如何将这些元素放入数组? 如下所示,我使用了scanf
,但效果并不理想。 任何建议,将不胜感激。
//User will pass ten numbers, separated by commas. This is to be put into an array.
#include <stdio.h>
int main ()
{
int A[10]; // array to contain in users input.
printf("Enter your numbers: ");
scanf("%d", &A[10]);
return 0;
}
您还必须在scanf
使用逗号:
for(int i=0; i<10; i++) { /* for each element in A */
if(0==scanf("%d,", &A[i])) { /* read a number from stdin into A[i] and then consume a commma (if any) */
break; /* if no digit was read, user entered less than 10 numbers separated by commas */
/* alternatively error handling if fewer than 10 is illegal */
}
}
我不会为你写全部内容。 但是我绝对可以帮上忙。 做到这一点的方法之一是:
fgets()
可能是? strtol()
可能是? ','
字符,并将指针设置为','
之后的下一个索引: strchr()
可能是? 下面的代码可以完成一半的工作。 剩下的唯一部分是从用户那里获取字符串并进行验证。 预先声明并初始化字符串的目的是更加强调对初学者来说似乎很复杂的数据的实际解析(无犯罪)。
在我们看下面的代码之前,让我们先阅读一些东西。
我已经承认,这可能不是实现它的最佳方法,我很高兴地同意,通过添加各种错误检查,可以以千种方式更好地改进下面的代码,但我留给您探索和实现。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
int i = 0, j = 0;
char *Str = "1,11,21,1211,111221,312211,1234,4321,123,789";
char *ptr;
long ret;
long array[10] = { [0 ... 9] = 0 };
// So, lets assume step 1 and 2 are taken care of.
// Iterate though the data for 10 times
for(i = 0; i < 10; i++)
{
ret = strtol(Str, &ptr, 10);
// Check if its a number
if(ret != 0)
{
// Its is a number!
// Put it in the array
array[j] = ret;
// Increment the index so that next number will not over-write the existing one
j++;
// Find the next ',' in the string
Str = strchr(Str, ',');
if(Str == NULL)
{
// Handle this condition that there are no more commas in the string!
break;
}
// Assuming that the ',' is found, increment the pointer to index next to ','
Str++;
}
}
// Print the array
for(i = 0; i < j; i++)
printf("%ld\n", array[i]);
}
这将输出以下输出:
1
11
21
1211
111221
312211
1234
4321
123
789
希望我能帮助您入门,祝您好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.