C:需要帮助从字符串中提取值

时间:2014-01-26 17:47:49

标签: c string

我试图从一个字符串中获得一段时间到几分钟。我得到一个这样的字符串:“1:50”。我需要将这些字符串中的分钟和秒提取到int变量中,然后以分钟为单位返回持续时间。所以我写了这个:

    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <conio.h>
    #include <string.h>

    int main()
    {
     char time[6]="01:30";
     int duration=0, minutes=0, seconds=0;
     int buffermin[3];
     int buffersec[3];
     int i=0;

     while(i<2)
     {
       sscanf(time[i],"%d%d",&buffermin[i]); //Get the first two characters in the string and store them in a intger array
       i++;
     }
     i=3;
     while(i<5)
     {
      sscanf(time[i],"%d%d",&buffersec[i]); //Get the last two characters in the                       string and store them in a integer array
      i++;
     }

     printf("%d %d %d %d", buffermin[0], buffermin[1], buffersec[0], buffersec[1]);

     getch();

     minutes=(buffermin[0]*10)+buffermin[1]; //Put values in array to one variable
     seconds=(buffersec[0]*10)+buffersec[1]; //Same as above

     seconds=seconds/60; //Turn the number of seconds to minutes

     duration=seconds+minutes; //Get total duration

     printf("The total duration is: %d\n",duration);  //Output total duration

     getch();
     exit(0);
     }    

为什么这不起作用,我该如何解决这个问题。任何例子都会非常感激。如果您有时间解释该示例的工作原理,请执行此操作。你可以看到编程仍然很差。

1 个答案:

答案 0 :(得分:1)

您应该真正了解如何正确使用sscanf。基本上,你想要实现的是:

#include <stdio.h>

int main() {
    char time[] = "01:27";

    int minutes;
    int seconds;

    // Must be double, not integer, otherwise decimal digits will be truncated
    double duration;

    // String has format "integer:integer"
    int parsed = sscanf(time, "%d:%d", &minutes, &seconds);

    // Check if input was valid    
    if (parsed < 2) {
        // String had wrong format, less than 2 integers parsed
        printf("Error: bad time format");
        return 1;
    }

    // Convert to minutes (mind the floating point division)
    duration = (seconds / 60.0) + minutes;

    printf("Duration: %.2f minutes\n", duration);

    return 0;
}