我想删除以下字符串:
char msg[30] ="Hello 13 1";
char *psh;
int num1;
int num2;
char s[30],s[30];
我试试这个,但是:
pch = strtok (msg," ");
while (pch != NULL)
{
printf ("%sn",pch);
pch = strtok (NULL, " ");
}
输出:
Hello
13
1
我只想让数字"13"等于num1,数字"1"等于num2:
printf("%dn",num1);
Output: 13
printf("%dn",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 ("%sn",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("%dn%dn", num1, num2);
return 0;
}
如果您有代码
pch = strtok (s," ");
while (pch != NULL)
{
printf ("%sn",pch);
pch = strtok (NULL, " ");
}
sscanf(sc, "%s %d %d", pch, &num1, &num2);
那么您有未定义的行为,因为您试图写入NULL
指针。
循环之后,pch
将是NULL
。
此外,num1
和num2
是字符数组(例如字符串),但您尝试将数字提取为整数。虽然数组足够大,可以容纳整数值,但如果您希望它们是实际整数,这仍然是错误的。
您还应该注意,strtok
会修改输入字符串。