首页 > 解决方案 > 在这种情况下如何将字符串转换为整数?

问题描述

作为我的 c 编程项目的一部分,我遇到了这个问题。我读取用户对 char 类型数组 ( char*str) 的输入,我需要将字符串输入的某些部分转换为整数。输入可能是“A smeagol 21 fire 22”

这是一些测试。我试图得到 x=40。此代码给出 x=-4324242。为什么这段代码不起作用?

#include <stdio.h>

int main(){
    char *uga[1];
    uga[0] = "10";
    printf("%s\n", uga[0]);
    int x = 50 - (int)uga[0];
    printf("%d",x);     
}

事先谢谢你。

标签: carraysstring

解决方案


您可以使用strtol,sscanfatoi将字符串转换为 int。例如:

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

int main() {
    char *str[3] = {"10", "20 test of strtol\n", "30"};
    int a = atoi(str[0]);
    printf("a = %d\n", a);
    char *ptr;
    long int b = strtol(str[1], &ptr, 10); // you can alse use strtoll for long long int
    printf("b = %ld, string: %s", b, ptr);
    int c;
    sscanf(str[2], "%d", &c);
    printf("c = %d\n", c);
    return 0;
}

输出:

a = 10
b = 20, string:  test of strtol
c = 30

在您的代码中,uga[0]是一个指向字符的指针。所以(int) uga[0]只需转换char指针的地址。


推荐阅读