gpt4 book ai didi

c - 字符串的子串并打印出来

转载 作者:太空宇宙 更新时间:2023-11-04 08:34:59 26 4
gpt4 key购买 nike

我想剖析以下字符串:

char msg[30] ="Hello 13 1";
char *psh;
int num1;
int num2;
char s[30],s[30];

我试试这个但是:

pch = strtok (msg," ");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ");
}

哪些输出:

 Hello
13
1

我只想让数字“13”等于 num1,数字“1”等于 num2:

    printf("%d\n",num1);

Output: 13


printf("%d\n",num2);

Output: 1

我尝试:

 sscanf(sc, "%s %d %d", &s, &num1, &num2);

哪些输出:

 Segmentation fault

谢谢

[编辑]

 char * pch
char s[30];
char sc[30];
char num1[30];
char num2[30];



pch = strtok (s," ");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ");
}

sscanf(sc, "%s %d %d", pch, &num1, &num2);

最佳答案

使用 sscanf功能:

sscanf(msg, "%s %d %d", s, &num1, &num2);

这会导致您的代码看起来像这样:

#include <stdio.h>
int main()
{
char msg[30] = "Hello 13 1";
int num1, num2;
char s[30];
sscanf(msg, "%s %d %d", s, &num1, &num2);
printf("%d\n%d\n", num1, num2);
return 0;
}

关于c - 字符串的子串并打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26651963/

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