将字符串转换为 int 是编程世界中反复出现的任务。尽管这是一项简单的任务,但许多编码人员在执行此操作时要么失败,要么感到困惑。转换主要是为了让我们可以对存储为字符串的数字执行操作。

有 3 种方法可以将字符串转换为 int,如下所示:

使用 atoi( )使用循环使用 sscanf()

 

1. 使用 atoi( ) 进行字符串转换

C 中的 atoi() 函数将字符数组或字符串文字作为参数,并以整数形式返回其值。它在  头文件中定义。

如果你仔细观察 atoi(),你会发现它代表:

 例如下列代码

#include

#include

int main()

{

char* str1 = "141";

char* str2 = "3.14";

// explicit type casting

int res1 = atoi(str1);

// explicit type casting

int res2 = atoi(str2);

printf("atoi(%s) is %d \n", str1, res1);

printf("atoi(%s) is %d \n", str2, res2);

return 0;

}

 输出

atoi(141) is 141

atoi(3.14) is 3

值得注意的是,atoi具有一定的局限性,对不同的字符串会有不同的执行结果 

#include

#include

int main()

{

char* str1 = "Geek 12345";

char* str2 = "12345 Geek";

int num1 = atoi(str1);

int num2 = atoi(str2);

printf("%d is of '%s'\n", num1, str1);

printf("%d is of '%s'\n", num2, str2);

return 0;

}

输出 

0 is of 'Geek 12345'

12345 is of '12345 Geek'

2. 使用循环

我们可以使用循环将字符串转换为整数,方法是逐个遍历字符串的每个元素并将数字字符与其 ASCII 值进行比较以获得它们的数值,并使用一些数学来生成整数。下面的示例演示了如何执行此操作。

例:

#include

#include

int main()

{

char* str = "4213";

int num = 0;

// converting string to number

for (int i = 0; str[i] != '\0'; i++) {

num = num * 10 + (str[i] - 48);

}

// at this point num contains the converted number

printf("%d\n", num);

return 0;

}

输出 

4213

注意:我们使用 str[i] – 48 将数字字符转换为它们的数值。例如,字符“5”的 ASCII 值是 53,因此 53 – 48 = 5,这是它的数值。 

当然,也可以将48替换成'0',更加便于记忆。 

3.使用 sscanf() 

我们可以使用 sscanf() 轻松地将字符串转换为整数。此函数从字符串中读取格式化的输入。

sscanf 的语法:

int sscanf (const char * source, const char * formatted_string, ...);

参数:

source – 源字符串。formatted_string – 包含格式说明符的字符串。... : – 变量参数列表,其中包含我们要存储输入数据的变量的地址。

这些参数的数量应至少与格式说明符存储的值数一样多。成功后,该函数返回填充的变量数。如果输入失败,在成功读取任何数据之前,将返回 EOF。

例:

#include

int main()

{

const char* str1 = "12345";

const char* str2 = "12345.54";

int x;

// taking integer value using %d format specifier for

// int

sscanf(str1, "%d", &x);

printf("The value of x : %d\n", x);

float y;

// taking float value using %f format specifier for

// float

sscanf(str2, "%f", &y);

printf("The value of x : %f\n", y);

return 0;

}

输出

The value of x : 12345

The value of x : 12345.540039

我们可以将 String 类型转换为 int 吗?

答案是否定的。如果我们使用类型转换将字符串转换为数字,我们将得到一个错误,如下例所示。

#include

int main()

{

string str = "8";

int num;

// Typecasting

num = (int)str;

return 0;

}

 输出

main.c: In function ‘main’:

main.c:9:11: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

9 | num = (int)str;

| ^

1683652612

解释: 由于 string 和 int 不在同一对象层次结构中,因此我们不能像在 double 到 int 或 float 到 int 转换的情况下那样执行隐式或显式类型转换。

在上面的代码中,我们可以看到输出给出了警告,其中包含任何垃圾值。因此,为了避免这种情况,我们使用上面指定的方法。 

本文引用了部分geeksforgeeks的内容

参考阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: