【问题标题】:Add user input to array in C将用户输入添加到C中的数组
【发布时间】:2014-11-09 13:41:34
【问题描述】:

我正在尝试用 C 语言创建读取用户输入的程序。正确的用户输入是[number][space][number]。我阅读了每个输入字符并检查是否只有一个空格。当'\n' 出现时,我需要将所有输入字符都存储在数组中。问题是我只有在'\n' 出现时才知道数组的大小。如何将输入写入数组? 这是我的代码:

#include <stdlib.h>
#include <stdio.h>

int array_size=0;
char input;
int spaces=0;

int main (){
while ((input = getchar())!=EOF){ 
array_size++;
if(input==' '){ //if user input a space
spaces++;
}

if(spaces>1){
fprintf(stderr, "You can input only one space in row\n");
spaces=0;
array_size=0;
continue;
}
if(input=='\n'){ //if thre is only one space and user inputs ENTER
char content[array_size+1];

//here I know array size and need to add to array all chars that were inputed

content[array_size-1]=='\0'; //content is a string
if((content[0]==' ')||(content[array_size-2]==' ')){
fprintf(stderr, "You can't input space only between numbers\n");
spaces=0;
array_size=0;
continue;
}

//then work with array

spaces=0;
array_size=0;
}

}
exit(0);
}

【问题讨论】:

    标签: c arrays input


    【解决方案1】:

    您的代码已损坏。这是一个例子。以此为起点。

    #include <stdlib.h>
    #include <stdio.h>
    #include <ctype.h>
    
    int main(void) {
      char input[10]; // 10 is just an example size
      int c;          // current character read
      int token_no = 0;
      // we read until EOF
      while ((c = getchar()) != EOF) {  //read chars while EOF
        if(c == '\n')  // or newline
          break;
        if (token_no % 2 == 0) {  // if no of token is even, then we expect a number
          if (isdigit(c)) {
            input[token_no++] = c;
          } else {
            printf("Expected number, exiting...\n");
            return -1;
          }
        } else {
          if (c == ' ') {
            input[token_no++] = c;
          } else {
            printf("Expected space, exiting...\n");
            return -1;
          }
        }
      }
      input[token_no++] = '\0'; // here you had ==, which was wrong
    
      printf("%s\n", input);
    
      return 0;
    }
    

    输出1:

    1 2 3
    1 2 3
    

    输出2:

    123
    Expected space, exiting...
    

    输出3:

    1       <- I have typed two spaces here
    Expected number, exiting...
    

    【讨论】:

      【解决方案2】:

      如果要动态分配和数组,确定大小后使用malloc

      int *a = (int*)malloc(sizeof(int) * size)
      

      或者看看这些答案:

      can size of array be determined at run time in c?

      How to declare the size of an array at runtime in C?

      【讨论】:

      • 请不要投射 malloc() 返回的内容。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      • 2021-08-02
      • 2016-07-24
      • 1970-01-01
      • 2016-05-03
      相关资源
      最近更新 更多