Dynamically allocate user inputted string

后端 未结 4 1368
不思量自难忘°
不思量自难忘° 2020-12-04 02:47

I am trying to write a function that does the following things:

  • Start an input loop, printing \'> \' each iteration.
  • Take whatever the
4条回答
  •  有刺的猬
    2020-12-04 03:06

    First of all, scanf format strings do not use regular expressions, so I don't think something close to what you want will work. As for the error you get, according to my trusty manual, the %a conversion flag is for floating point numbers, but it only works on C99 (and your compiler is probably configured for C90)

    But then you have a bigger problem. scanf expects that you pass it a previously allocated empty buffer for it to fill in with the read input. It does not malloc the sctring for you so your attempts at initializing str to NULL and the corresponding frees will not work with scanf.

    The simplest thing you can do is to give up on n arbritrary length strings. Create a large buffer and forbid inputs that are longer than that.

    You can then use the fgets function to populate your buffer. To check if it managed to read the full line, check if your string ends with a "\n".

    char str[256+1];
    while(true){
        printf("> ");
        if(!fgets(str, sizeof str, stdin)){
            //error or end of file
            break;
        }
    
        size_t len = strlen(str);
        if(len + 1 == sizeof str){
            //user typed something too long
            exit(1);
        }
    
        printf("user typed %s", str);
    }
    

    Another alternative is you can use a nonstandard library function. For example, in Linux there is the getline function that reads a full line of input using malloc behind the scenes.

提交回复
热议问题