首页 > 解决方案 > 分段故障。将字符串转换为整数

问题描述

我有一个问题,我试图将字符串指针数组中的值转换为整数值:token [1]。但是,每当我没有在第一个索引处指定整数时,我都会遇到分段错误,在某些情况下我不需要数字。例如,如果我只想输入命令:list. 之后我会遇到分段错误。如果整数存在或不存在,如何将 token[1] 处的字符串值转换为整数?

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main(){
    int ch,  n = 1;
    int i = 0;
    int val = 0;
    char str[512], *token[5], *act_token;
    while(1){

            printf("Enter text: ");
            while((ch = getchar()) != '\n')
                    str[i++] = ch;
            str[i] = '\0';
            i = 0;                

            printf("string: %s\n", str);

            int spaces = 0;
            for(int counter  = 0; counter < strlen(str) + 1; counter++){
                    if(str[counter] == ' '){
                            spaces++;
                    }
            }
            printf("Spaces: %d\n", spaces); 
            strtok(str, " ");
            while(n <= spaces && (act_token = strtok(NULL, " "))){
                    token[n] = act_token;
                    n++;

            }
            token[n] = NULL;
            n = 1;
    //      printf("token[1]: %s\n", token[1]);     
            for(int x = 1; x < spaces+1; x++){
                    printf("token[%d]: %s\n", x, token[x]);

            } 

            if(isdigit(atoi(token[1])) != 0){
                    val = atoi(token[1]);
            }
            printf("value:%d\n", val);
    }

    return 0;

}

标签: c

解决方案


我不知道我对你的理解是否正确。但是,我只是添加了一些检查以防止在代码的不同点发生段错误。用“foo 3 33”测试。格式很差。

int main(){


    int ch,  n = 1;
    int i = 0;
    int val = 0;
    #define TOKEN_SZ 5
    char str[512], *token[TOKEN_SZ+1], *act_token;
    while(1){
        printf("Enter text: ");
        while((ch = getchar()) != '\n')
                str[i++] = ch;
        str[i] = '\0';
        i = 0;                

        printf("string: %s\n", str);

        int spaces = 0;
        for(int counter  = 0; counter < strlen(str) + 1; counter++){
                if(str[counter] == ' '){
                        spaces++;
                }
        }
        printf("Spaces: %d\n", spaces); 
        n=0;
        strtok(str, " ");
        while(n<TOKEN_SZ && n <= spaces && (act_token = strtok(NULL, " "))){
                token[n] = act_token;
                n++;
        }
        token[n] = NULL;

        for(int i=0; token[i]; i++){
                printf("%d token[%d]: %s\n", n,i, token[i]);

        } 

        if(n>0 && (atoi(token[0])) != 0){
                val = atoi(token[0]);
        }
        printf("value:%d\n", val);
}
return 0;

}

更新

bash> ./a.out
输入文本:列表 2 4
字符串:列表 2 4
空间:2
2 令牌[0]:2
2 令牌[1]:4
值:2
输入文字:

推荐阅读