做小米笔试的时候遇到了要直接写输入读取带逗号的数组,差点没写出来
输入:
5
1,2,3,4,999
输出
1 2 3 4 999
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
int n,len;
int *arr;
char tmp[10];
char str[1000];
scanf("%d", &n); //数组大小
arr = (int*)malloc(sizeof(int) * n);
scanf("%s", str); //以字符串形式读取
len = strlen(str);
for (int i = 0,j=0; i < n; i++) {
sscanf(str+j, "%[^',']", tmp);
arr[i] = atoi(tmp);
while (j<len && str[j++] != ',');
}
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}
也可以使用strtok函数:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char str[20]= "11,22,33,44,55";
char* p;
const char* delim = ",";
p = strtok(str, delim);
while (p != NULL) {
printf("%d ", atoi(p));
p = strtok(NULL, delim);
}
return 0;
}