如何将字符串值转换为数值?

时间:2018-12-09 07:07:44

标签: c string

我已尝试将此代码将Str []字符串分成2个字符串,但是我的问题是“我想将John(name)分为字符串,将100(marks)分为整数”,我该怎么办?建议?

   #include <stdio.h>
   #include <string.h>

    void main()
    {
        char Str[] = "John,100";
        int i, j, xchange;
        char name[50];
        char marks[10];
        j = 0; xchange = 0;

        for(i=0; Str[i]!='\0'; i++){
            if(Str[i]!=',' && xchange!=-1){
                name[i] = Str[i];
            }else{
                xchange = -1;
            }
            if(xchange==-1){
                marks[j++] = Str[i+1];
            }
        }
        printf("Student name is %s\n", name);
        printf("Student marks is %s", marks);
    }

1 个答案:

答案 0 :(得分:1)

  

如何将“ John,100”分成2个字符串?

共有三种常用方法:

  1. 使用strtok()将字符串拆分为单独的标记。这将修改原始字符串,但是实现起来非常简单:

    int main(void)
    {
        char  line[] = "John,100;passed";
        char *name, *score, *status;
    
        /* Detach the initial part of the line,
           up to the first comma, and set name
           to point to that part. */
        name = strtok(line, ",");
    
        /* Detach the next part of the line,
           up to the next comma or semicolon,
           setting score to point to that part. */
        score = strtok(NULL, ",;");
    
        /* Detach the final part of the line,
           setting status to point to it. */
        status = strtok(NULL, "");
    

    请注意,如果您更改char line[] = "John,100";,则status将是NULL,但是代码可以安全地运行。

    因此,实际上,如果要求所有三个字段都存在于line中,那么确保最后一个字段不是NULL就足够了:

        if (!status) {
            fprintf(stderr, "line[] did not have three fields!\n");
            return EXIT_FAILURE;
        }
    
  2. 使用sscanf()转换字符串。例如,

        char  line[] = "John,100";
        char  name[20];
        int   score;
    
        if (sscanf(line, "%19[^,],%d", name, &score) != 2) {
            fprintf(stderr, "Cannot parse line[] correctly.\n");
            return EXIT_FAILURE;
        }
    

    在这里,19指的是name中的字符数(始终为字符串末尾nul字符'\0'保留一个)和{{1} }是一个字符串转换,除了逗号以外,都消耗了所有内容。 [^,]转换为%d。返回值是成功的转换次数。

    这种方法不会修改原始字符串,它使您可以尝试许多不同的解析模式;只要先尝试最复杂的一种,就可以允许添加很少代码的多种输入格式。当以2D或3D向量作为输入时,我会定期执行此操作。

    缺点是int(scanf系列中的所有函数)都忽略了溢出。例如,在32位架构上,最大的sscanf()int,但是scanf函数会很乐意转换例如从21474836479999999999(或其他值!)而不会返回错误。您只能假设数字输入是合理的并且在限制之内;您无法验证。

  3. 使用辅助函数标记和/或解析字符串。

    通常,助手功能类似于

    1410065407

    其中char *parse_string(char *source, char **to); char *parse_long(char *source, long *to); 是指向要解析的字符串中下一个字符的指针,而source是指向要存储解析的值的指针;或

    to

    其中char *next_string(char **source); long next_long(char **source); 是指向要解析的字符串中下一个字符的指针,返回值是提取的令牌的值。

    这些往往比上面的更长,如果是我写的,那么他们接受的输入会很偏执。 (我想让我的程序抱怨,如果它们的输入不能可靠地解析,而不是无声地产生垃圾。)


如果数据是从文件中读取的CSV(逗号分隔值)的某种变体,则正确的方法是另一种方法:与其逐行读取文件,不如逐行读取文件令牌令牌。

唯一的“技巧”是记住记号结尾的分隔符(您可以使用source),并使用其他函数(读取和忽略当前记录中的其余记号) ,)使用换行符。

相关问题