gpt4 book ai didi

c - 从 C 中的字符串中提取整数

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:56 25 4
gpt4 key购买 nike

我正在尝试从字符串 add 56 89 29 中提取所有数字。我的代码有问题,我无法弄清楚。输出如下所示:

Current no: 56
Current no: 89
Current no: 9
Current no: 29
Current no: 9
Current no: 9
Current no: 0
Current no: 0

我希望这样:

Current no: 56
Current no: 89
Current no: 29
Current no: 29
Current no: 29
Current no: 29

有更好的方法可以做到这一点,但我想知道这个实现有什么问题。

#include <string.h>
#include <stdio.h>

int main(int argc, char * argv[]){
char temp[100];
char op[3];
char *buf = "add 56 89 29";
int offset = 0;
int rcount = 0;
int lastno = -999;
int currno;
bzero(&temp, sizeof(temp));
sscanf(buf, "%s", op); // Get the operator (add)
if(!strcmp(op, "add")){
while(1){
sscanf(buf + offset + 4, "%s", temp); // strlen("add ") == 4
currno = atoi(temp);
offset += strlen(temp);
if(currno == lastno){
rcount++;
// Repeating numbers means string finished
if(rcount == 3){
break;
}
}
printf("Current no: %d\tOffset: %d\n", currno, offset + 4);
lastno = currno;
}
}
return 0;
}

提前致谢!

最佳答案

"%n" 说明符将记录一次扫描使用的字符数。可以将结果添加到偏移量以在字符串中前进。

#include <string.h>
#include <stdio.h>

int main(int argc, char * argv[]){
char temp[100];
char op[4];
char *buf = "add 56 89 29";
int offset = 0;
int used = 0;
int rcount = 0;
int lastno = -999;
int currno;
bzero(&temp, sizeof(temp));
sscanf(buf, "%3s%n", op, &used); // Get the operator (add)
offset += used;
if(!strcmp(op, "add")){
while( ( sscanf(buf + offset, "%99s%n", temp, &used)) == 1) {
currno = atoi(temp);
offset += used;
printf("Current no: %d\tOffset: %d\n", currno, offset);
lastno = currno;
}
}
return 0;
}

关于c - 从 C 中的字符串中提取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30003379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com