如何将数字存储在以空格分隔的数组中?该程序仅输入第一个数字
#include <string.h>
#include <stdio.h>
int main(void) {
char array[255];
int i=0;
char enter;
printf("enter number separated by space, enter to cofirm: ");
while ((enter= (char)getchar()) != ' ')
{
array[i++]= enter;
}
printf("the string is %s\n", array);
return 0;
}
最佳答案
循环while ((enter= (char)getchar()) != ' ')
在找到第一个空格后立即停止获取值。
您想要的是这样的东西:
#include <string.h>
#include <stdio.h>
int main(void) {
char array[255];
int i=0;
char enter;
printf("enter number separated by space, enter to cofirm: ");
while ((enter= (char)getchar()) != '\n') { //only stops when return is found
array[i++]= enter;
}
array[i] = '\0'; // terminate string
printf("the string is %s\n", array);
return 0;
}
编辑
好吧,如果您只想将数字字符串作为用空格分隔的字符,则可以使用fgets:
#include <string.h>
#include <stdio.h>
int main(void) {
char array[255];
int i=0;
int enter;
printf("enter number separated by space, enter to cofirm: ");
fgets (array, sizeof(array), stdin);
printf("the string is %s\n", array);
return 0;
}
编辑2
好的,最后一个,如果您要按照注释中的说明将整数存储在数组中,则可以使用scanf,请注意整数或数组溢出。
样品
#include <string.h>
#include <stdio.h>
int main(void) {
int array[255];
int i = 0;
printf("enter number separated by space, enter to cofirm: ");
while(scanf("%d",&(array[i]))){
printf("the string is %d\n", array[i++]);
if(getchar() == '\n')
break;
}
}
关于c - 将数字存储在以空格分隔的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59984640/