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

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

问题描述

我有了整数字符串,我试图让所有的整数到另一个阵列。当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.

任何想法有什么不对?谢谢你。

Any idea what's wrong? Thanks.

推荐答案

同样的字符串指针每次调用时间的推移的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的不动,扫描相同的整数每次! C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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