首页主机资讯C语言字符串怎么转换为数字

C语言字符串怎么转换为数字

时间2023-12-21 16:43:03发布访客分类主机资讯浏览795
导读:在C语言中,可以使用标准库函数atoi、atof或sscanf将字符串转换为数字。 使用atoi函数将字符串转换为整数: #include <stdio.h> #include <stdlib.h> int m...

在C语言中,可以使用标准库函数atoiatofsscanf将字符串转换为数字。

  1. 使用atoi函数将字符串转换为整数:
#include stdio.h>
    
#include stdlib.h>


int main() {
    
    char str[] = "12345";
    
    int num = atoi(str);
    
    printf("The converted number is: %d\n", num);
    

    return 0;

}
    
  1. 使用atof函数将字符串转换为浮点数:
#include stdio.h>
    
#include stdlib.h>


int main() {
    
    char str[] = "3.14";
    
    float num = atof(str);
    
    printf("The converted number is: %.2f\n", num);
    

    return 0;

}
    
  1. 使用sscanf函数从字符串中提取数字:
#include stdio.h>


int main() {
    
    char str[] = "The price is $12.50";
    
    float price;
    
    
    sscanf(str, "The price is $%f", &
    price);
    
    printf("The converted number is: %.2f\n", price);
    

    return 0;

}
    

以上示例中,分别使用atoiatofsscanf将字符串转换为整数、浮点数和提取指定格式的数字。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: C语言字符串怎么转换为数字
本文地址: https://pptw.com/jishu/578816.html
C++中的std::bind怎么使用 springboot怎么修改注解功能

游客 回复需填写必要信息