使用scanf()的动态分配 [英] Dynamic allocation with scanf()
问题描述
我的问题与此一个完全相同。也就是说,我试图使用 scanf()
接收一个不确定长度的字符串,我想要 scanf()
为它动态分配内存。
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 dynamically allocate memory for it.
但是,在我的情况,我使用VS2010。据我所见,MS的 scanf()没有或m修饰符用于扫描字符串。有没有办法做到这一点(除了一次接收一个字符输入)?
However, in my situation, I am using VS2010. As far as I can see, MS's scanf() doesn't have an a or m modifier for when scanning for strings. Is there any way to do this (other than receiving input one character at a time)?
推荐答案
如果你想使用 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.
这篇关于使用scanf()的动态分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!