更新时间:2023-11-02 17:18:10
如果你想使用 scanf
你可以分配一个足够大的缓冲区来保存任何可能的值,比如1024字节,然后使用1024的最大字段宽度说明符。
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.
m
和 a
是特定的非标准GNU扩展,因此Microsofts编译器不支持他们。
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.
下面是使用 scanf
读取设置的示例,退出:
#include
#include
#include
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;
}
下面是一个示例 settings.conf
cake = 5
three = 3
answertolifeuniverseandeverything = 42
charcoal = -12
您可以阅读有关 scanf
。
You can read more about scanf
on the manpages.
您当然可以使用 getline()
。
如果你想多做一些你想达到的目标,你可能会得到一个更好的答案。
If you would go into a little more what you are trying to achieve you could maybe get an better answer.