我在C编程项目中遇到了这个问题。我读取了输入到char类型数组(char*str
)的用户,并且需要将字符串输入的某些部分转换为整数。输入可能是“ 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);
}
谢谢你。
将char
指针或数组强制转换为int
或其他数字类型的类型不会为您提供字符串中文本的数字值。
您应该使用函数strtol
(带符号),strtoul
(带符号)来完成此操作:
char *str = "123ABC";
char *pStop;
// (Arguments: string to parse, pointer to character that stops the parse, base/radix)
int value = strtol(str, &pStop, 10);
[此后,value
将为123
,并且pStop
将指向str
中的'A'。如果您不关心它,则第二个参数可以是NULL
,但是对于处理非数字文本之间包含很多数字的字符串很有用。
您的代码中有两个问题。
char uga[max_size_of_your_string] = "Initialization if you want to";
(int)uga[0];
无法按预期工作,因为您正在尝试将地址转换为整数。我建议您正确声明字符串uga
,并在此处查看将数字字符串转换为整数的不同方法:How to convert a string to integer in C?