c - 在这种情况下如何将字符串转换为整数?
问题描述
作为我的 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);
}
事先谢谢你。
解决方案
您可以使用strtol
,sscanf
或 atoi
将字符串转换为 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
指针的地址。
推荐阅读
- c++ - __m256 数组上的 Visual Studio 2019 C6385 / C6386(缓冲区溢出警告)
- python - 登录后如何重定向到用户个人资料页面?
- python - 如何将 .properties 转换为 linux env 导出文件
- flutter - 如何在一个屏幕上听两个不同的未来?
- java - 在 Vert.x 应用程序中使用 Project Reactor
- angular - 用于引用外部库的 Typescript 虚拟文件夹
- python-3.x - Twint 模块并从推文创建数据框
- dax - DAX 时间智能函数 - 有没有办法获取底层 DAX 代码?
- java - java 8中Date对象的after函数问题
- python - 循环从列表中创建多个数据框