我想删除以下字符串:
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);
答案 0 :(得分:1)
使用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;
}
答案 1 :(得分:1)
如果你有代码
pch = strtok (s," ");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ");
}
sscanf(sc, "%s %d %d", pch, &num1, &num2);
然后你有undefined behavior,因为你试图写一个NULL
指针。
循环结束后,pch
将为NULL
。
此外,num1
和num2
是字符数组(例如字符串),但您尝试将数字提取为整数。虽然数组足够大以适应整数值,但如果你想要它们作为实际整数,它仍然是错误的。
您还应注意strtok
修改输入字符串。