gpt4 book ai didi

c - sscanf 扫描特定大小的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:43 24 4
gpt4 key购买 nike

我只想在下面的代码中扫描“sizeof(out)”字符串“out”。 'input' 字符串可能比 out 多,因此 out 会造成溢出。格式字符串也可以用 sprintf/snprintf 完成。

#include<stdio.h>
#define BUFSZ 4

int main()
{
char input[16]="#123 abcdefg";
int k;
char out[BUFSZ];

sscanf(input,"#%d %s",&k,out);
/* Something like %ns where n is the size of out in above line */

printf("%d\n",k);
printf("%s\n",out);
return 0;
}

最佳答案

#include<stdio.h>

#define BUFSZ 4

#define _S(x) #x
#define S(x) _S(x)

int main(void){
char input[16]="#123 abcdefg";
int k;
char out[BUFSZ+1];

sscanf(input,"#%d %" S(BUFSZ) "s",&k,out);//field size -1 for End Of String(\0)

printf("%d\n",k);
printf("%s\n",out);
return 0;
}

关于c - sscanf 扫描特定大小的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17759171/

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