sscanf不移动,每次扫描相同的整数 [英] sscanf doesn't move, scanning same integer everytime

查看:140
本文介绍了sscanf不移动,每次扫描相同的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含整数的字符串,并且我试图将所有整数放入另一个数组中.当sscanf找不到int时,我希望循环停止.因此,我做了以下事情:

I have a string that has ints and I'm trying to get all the ints into another array. When sscanf fails to find an int I want the loop to stop. So, I did the following:

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.

这导致startarray的所有元素成为startbuffer中的第一个字符. sscanf可以正常工作,但是它不会移动到仅停留在第一个位置的下一个int上.

This results in having all the elements of startarray to be the first char in startbuffer. sscanf works fine but it doesn't move onto the next int it just stays at the first position.

有什么想法吗?谢谢.

推荐答案

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

The same string pointer is passed each time you call sscanf. If it were to "move" the input, it would have to move all the bytes of the string each time which would be slow for long strings. Furthermore, it would be moving the bytes that weren't scanned.

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

Instead, you need to implement this yourself by querying it for the number of bytes consumed and the number of values read. Use that information to adjust the pointers yourself.

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;
}

这篇关于sscanf不移动,每次扫描相同的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆