C++ 中字符串与数字的相互转换
在本节中,我们将了解如何将字符串转换为数字以及将数字转换为字符串。首先,我们将了解如何将字符串转换为数字。
字符串到数字的转换
在这里,我们将了解如何将数字字符串转换为整数类型数据。我们可以使用 atoi() 函数来解决此问题。此函数以字符串作为输入,并将其转换为整数数据。
atoi() 函数位于 <cstdlib> 库中。
Input: A number string “1234” Output: 1234
算法
Step 1:Take a number string Step 2: Convert it to integer using atoi() function Step 3: Print the result. Step 4: End
示例代码
#include<iostream>
#include<cstdlib>
using namespace std;
main() {
int n;
char num_string[20] = "1234";
n = atoi(num_string);
cout << n;
}输出
1234
数字到字符串的转换
在本节中,我们将了解如何将数字(整数、浮点数或任何其他数字类型数据)转换为字符串。
逻辑非常简单。在这里,我们将使用 sprintf() 函数。此函数用于将某些值或行打印到字符串中,而不是在控制台中打印。这是 printf() 和 sprintf() 之间的唯一区别。这里第一个参数是字符串缓冲区,我们希望将数据保存到其中。
Input: User will put some numeric value say 42.26 Output: This program will return the string equivalent result of that number like “42.26”
算法
Step 1: Take a number from the user Step 2: Create an empty string buffer to store result Step 3: Use sprintf() to convert number to string Step 4: End
示例代码
#include<stdio.h>
main() {
char str[20]; //create an empty string to store number
float number;
printf("Enter a number: ");
scanf("%f", &number);
sprintf(str, "%f", number);//make the number into string using sprintf function
printf("You have entered: %s", str);
}输出
Enter a number: 46.3258 You have entered: 46.325802
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP