c - 将数字存储在以空格分隔的数组中

标签 c

如何将数字存储在以空格分隔的数组中?该程序仅输入第一个数字

#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/

相关文章:

c++ - 结束使用 ShellExecute 函数启动的 C++ 程序的最佳方法是什么?

C Valgrind - 条件跳转取决于未初始化的值

c - Linux内核模块编程中_do_fork()的问题

c++ - 在 HP-UX、Solaris 或 AIX 上是否有任何 getifaddrs() 替代方案?

c - 词典匹配/拼写检查程序

c - 了解 fwrite() 行为

c - C 中的 strcat 不兼容类型错误

c - 如何在 Visual Studio Code 中设置混合 C/Z80 汇编程序工具链

c - 如何有效地添加 2 个不同大小的链表

c - 为什么 less 改变输出顺序?