sscanf不移动,每次扫描相同的整数

Min*_*any 13 c string input scanf

我有一个包含整数的字符串,我正在尝试将所有内容放入另一个数组中.当sscanf找不到int我想要循环停止时.所以,我做了以下事情:

int i;
int getout = 0;
for (i = 0; i < bsize && !getout; i++) {
    if (!sscanf(startbuffer, "%d", &startarray[i])) {
        getout = 1;
    }
}
//startbuffer is a string, startarray is an int array.
Run Code Online (Sandbox Code Playgroud)

这导致将所有元素startarray作为第一个char startbuffer. sscanf工作正常但它不会移动到下一个int它只是停留在第一个位置.

知道什么是错的吗?谢谢.

Pot*_*ter 15

每次调用时都会传递相同的字符串指针sscanf.如果要"移动"输入,则每次都必须移动字符串的所有字节,这对于长字符串来说会很慢.此外,它将移动扫描的字节.

相反,您需要自己通过查询消耗的字节数和读取的值的数量来实现它.使用该信息自己调整指针.

int nums_now, bytes_now;
int bytes_consumed = 0, nums_read = 0;

while ( ( nums_now = 
        sscanf( string + bytes_consumed, "%d%n", arr + nums_read, & bytes_now )
        ) > 0 ) {
    bytes_consumed += bytes_now;
    nums_read += nums_now;
}
Run Code Online (Sandbox Code Playgroud)


wai*_*kuo 5

将字符串转换为流,然后可以使用 fscanf 获取整数。尝试这个。 http://www.gnu.org/software/libc/manual/html_node/String-Streams.html