How can I read an input string of unknown length?

前端 未结 10 1337
逝去的感伤
逝去的感伤 2020-11-22 07:56

If I don\'t know how long the word is, I cannot write char m[6];,
The length of the word is maybe ten or twenty long. How can I use scanf to ge

相关标签:
10条回答
  • 2020-11-22 08:36

    Enter while securing an area dynamically

    E.G.

    #include <stdio.h>
    #include <stdlib.h>
    
    char *inputString(FILE* fp, size_t size){
    //The size is extended by the input with the value of the provisional
        char *str;
        int ch;
        size_t len = 0;
        str = realloc(NULL, sizeof(char)*size);//size is start size
        if(!str)return str;
        while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
            str[len++]=ch;
            if(len==size){
                str = realloc(str, sizeof(char)*(size+=16));
                if(!str)return str;
            }
        }
        str[len++]='\0';
    
        return realloc(str, sizeof(char)*len);
    }
    
    int main(void){
        char *m;
    
        printf("input string : ");
        m = inputString(stdin, 10);
        printf("%s\n", m);
    
        free(m);
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 08:36

    If I may suggest a safer approach:

    Declare a buffer big enough to hold the string:

    char user_input[255];

    Get the user input in a safe way:

    fgets(user_input, 255, stdin);

    A safe way to get the input, the first argument being a pointer to a buffer where the input will be stored, the second the maximum input the function should read and the third is a pointer to the standard input - i.e. where the user input comes from.

    Safety in particular comes from the second argument limiting how much will be read which prevents buffer overruns. Also, fgets takes care of null-terminating the processed string.

    More info on that function here.

    EDIT: If you need to do any formatting (e.g. convert a string to a number), you can use atoi once you have the input.

    0 讨论(0)
  • 2020-11-22 08:38

    Take a character pointer to store required string.If you have some idea about possible size of string then use function

    char *fgets (char *str, int size, FILE* file);`
    

    else you can allocate memory on runtime too using malloc() function which dynamically provides requested memory.

    0 讨论(0)
  • 2020-11-22 08:40

    i also have a solution with standard inputs and outputs

    #include<stdio.h>
    #include<malloc.h>
    int main()
    {
        char *str,ch;
        int size=10,len=0;
        str=realloc(NULL,sizeof(char)*size);
        if(!str)return str;
        while(EOF!=scanf("%c",&ch) && ch!="\n")
        {
            str[len++]=ch;
            if(len==size)
            {
                str = realloc(str,sizeof(char)*(size+=10));
                if(!str)return str;
            }
        }
        str[len++]='\0';
        printf("%s\n",str);
        free(str);
    }
    
    0 讨论(0)
  • 2020-11-22 08:43

    Read directly into allocated space with fgets().

    Special care is need to distinguish a successful read, end-of-file, input error and out-of memory. Proper memory management needed on EOF.

    This method retains a line's '\n'.

    #include <stdio.h>
    #include <stdlib.h>
    
    #define FGETS_ALLOC_N 128
    
    char* fgets_alloc(FILE *istream) {
      char* buf = NULL;
      size_t size = 0;
      size_t used = 0;
      do {
        size += FGETS_ALLOC_N;
        char *buf_new = realloc(buf, size);
        if (buf_new == NULL) {
          // Out-of-memory
          free(buf);
          return NULL;
        }
        buf = buf_new;
        if (fgets(&buf[used], (int) (size - used), istream) == NULL) {
          // feof or ferror
          if (used == 0 || ferror(istream)) {
            free(buf);
            buf = NULL;
          }
          return buf;
        }
        size_t length = strlen(&buf[used]);
        if (length + 1 != size - used) break;
        used += length;
      } while (buf[used - 1] != '\n');
      return buf;
    }
    

    Sample usage

    int main(void) {
      FILE *istream = stdin;
      char *s;
      while ((s = fgets_alloc(istream)) != NULL) {
        printf("'%s'", s);
        free(s);
        fflush(stdout);
      }
      if (ferror(istream)) {
        puts("Input error");
      } else if (feof(istream)) {
        puts("End of file");
      } else {
        puts("Out of memory");
      }
      return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 08:44

    There is a new function in C standard for getting a line without specifying its size. getline function allocates string with required size automatically so there is no need to guess about string's size. The following code demonstrate usage:

    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main(void)
    {
        char *line = NULL;
        size_t len = 0;
        ssize_t read;
    
        while ((read = getline(&line, &len, stdin)) != -1) {
            printf("Retrieved line of length %zu :\n", read);
            printf("%s", line);
        }
    
        if (ferror(stdin)) {
            /* handle error */
        }
    
        free(line);
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题