Dynamic allocation with scanf()

后端 未结 5 1960
孤街浪徒
孤街浪徒 2021-01-25 06:58

My question is exactly the same as this one. That is, I\'m trying to use scanf() to receive a string of indeterminate length, and I want scanf() to dyn

5条回答
  •  猫巷女王i
    2021-01-25 07:21

    If you want to use scanf you could just allocate a large enough buffer to hold any possible value, say 1024 bytes, then use a maximum field width specifier of 1024.

    The m and a are specific non-standard GNU extensions, so thats why Microsofts compiler does not support them. One could wish that visual studio did.

    Here is an example using scanf to read settings, and just print them back out:

    #include 
    #include 
    #include 
    
    int
    main( int argc, char **argv )
    {   // usage ./a.out < settings.conf
    
        char *varname;
        int value, r, run = 1;
    
        varname = malloc( 1024 );
    
        // clear errno
        errno = 0;
    
        while( run )
        {   // match any number of "variable = #number" and do some "processing"
    
            // the 1024 here is the maximum field width specifier.
            r = scanf ( "%1024s = %d", varname, &value );
            if( r == 2 )
            {   // matched both string and number
                printf( " Variable %s is set to %d \n", varname, value );
            } else {
                // it did not, either there was an error in which case errno was
                // set or we are out of variables to match
                if( errno != 0 )
                {   // an error has ocurred.
                    perror("scanf");
                }
                run = 0;
            }
        }
    
        return 0;
    }
    

    Here is an example settings.conf

    cake = 5
    three = 3
    answertolifeuniverseandeverything = 42
    charcoal = -12
    

    You can read more about scanf on the manpages.

    And you can of course use getline(), and after that parse character after character.

    If you would go into a little more what you are trying to achieve you could maybe get an better answer.

提交回复
热议问题