【问题标题】:substring of a string and print it out字符串的子字符串并打印出来
【发布时间】:2014-12-26 10:23:39
【问题描述】:

我想剖析以下字符串:

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);

【问题讨论】:

  • 不要对字符串使用地址运算符 (&),它们已经是指针(或者在数组的情况下衰减为指针)。
  • 如果您以前从未尝试过使用调试器,那么现在是最佳时机。如果您在调试器中运行程序,它将在崩溃的位置停止。然后,您可以查看函数调用堆栈,甚至沿着调用堆栈向上走,这样您就可以看到您的代码(如果您还没有在那里),然后检查变量的值。至少,请使用调试信息构建(将-g 标志添加到gcc)并在调试器中运行并编辑问题以包含bt 调试器命令的输出(显示函数调用堆栈,又名回溯)。

标签: c string substring strtok strncpy


【解决方案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

另外,num1num2 是字符数组(例如字符串),但您尝试将数字提取为整数。虽然数组足够大以容纳整数值,但如果您希望它们作为实际整数仍然是错误的。

您还应该注意strtok 修改了输入字符串。

【讨论】:

    【解决方案2】:

    使用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;
    }
    

    【讨论】:

    • 在依赖具有正确值的变量之前,您应该检查sscanf() 的返回值。
    猜你喜欢
    • 1970-01-01
    • 2017-03-30
    • 2015-08-24
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多