简体   繁体   English

如何从字符中提取整数

[英]How to Extract integer from character

I have this code:我有这个代码:

            int num[10]   ;            
            sscanf(msg, "%d%d%d%d%", &num[0], &num[1], &num[2], &num[3]); 
            int x = num[0]; // integer
            int y = num[1]; // integer
            int z = num[2]; // integer
            int c = num[3]; // integer

I got problem from the above code, when I write '131249', so the result is:我从上面的代码中遇到问题,当我写“131249”时,结果是:

x = 177 
y = -8755
z = -21206
c = -246

but the expected value should但期望值应该

x = 13 
y = 12
z = 4
c = 9

How to have the expected value, is there any wrong in my code ?如何获得预期值,我的代码有什么问题吗?

If your values length is fixed, you may want to specify the lenght of each value you're trying to capture.如果您的值长度是固定的,您可能需要指定您尝试捕获的每个值的长度。 Ex :前任 :

sscanf(msg, "%2d%2d%1d%1d%", &num[0], &num[1], &num[2], &num[3]);

It's hard to believe that if you did a printf of x that you'd see 177. It should be 131249 based on your code.很难相信,如果您执行 x 的 printf,您会看到 177。根据您的代码,它应该是 131249。 Try Nicolas' suggestion.试试尼古拉斯的建议。 You might also want to initialize your num array, ie您可能还想初始化您的 num 数组,即

int num[10] = {0}; int num[10] = {0};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM