有许多情况需要将数字转换为字符串或将字符串转换为数字。本文中提到了一些实现此任务的方法。
将字符串转换为数字
方法1:使用stringstream类或sscanf()
方法2:使用stoi()或atoi()进行字符串转换
方法3:使用boost lexical_cast
Boost库提供了一个内置函数lexical_cast("string"),该函数直接将字符串转换为数字。如果输入无效,则返回异常“bad_lexical_cast”。
//C++ code to demonstrate working of lexical_cast() #include #include // for lexical_cast() #include // for string using namespace std; int main() { string str = "5"; string str1 = "6.5"; // Initializing f_value with casted float // f_value is 6.5 float f_value = boost::lexical_cast(str1); // Initializing i_value with casted int // i_value is 5 int i_value = boost::lexical_cast(str); //Displaying casted values cout << "The float value after casting is : "; cout << f_value <
输出:
The float value after casting is : 6.5The int value after casting is : 5
将数字转换为字符串
方法1:使用字符串流
在此方法中,字符串流声明一个流对象,该对象首先将一个数字作为流插入对象,然后使用“str()”跟随数字到字符串的内部转换。
// C++ code to demonstrate string stream method // to convert number to string. #include #include // for string streams #include // for string using namespace std; int main() { int num = 2016; // declaring output string stream ostringstream str1; // Sending a number as a stream into output // string str1 << num; // the str() coverts number into string string geek = str1.str(); // Displaying the string cout << "The newly formed string from number is : "; cout << geek << endl; return 0; }
输出:
The newly formed string from number is : 2016
方法2:使用to_string()
该函数接受一个数字(可以是任何数据类型),并以所需的字符串形式返回该数字。
// C++ code to demonstrate "to_string()" method // to convert number to string. #include #include // for string and to_string() using namespace std; int main() { // Declaring integer int i_val = 20; // Declaring float float f_val = 30.50; // Conversion of int into string using // to_string() string stri = to_string(i_val); // Conversion of float into string using // to_string() string strf = to_string(f_val); // Displaying the converted strings cout << "The integer in string is : "; cout << stri << endl; cout << "The float in string is : "; cout << strf << endl; return 0; }
输出:
The integer in string is : 20The float in string is : 30.500000
方法3:使用boost lexical_cast
与字符串转换类似,“lexical_cast()”函数保持不变,但是这次参数列表修改为“lexical_cast(numeric_var)”。
// C++ code to demonstrate "lexical_cast()" method // to convert number to string. #include // for lexical_cast() #include // for string using namespace std; int main() { // Declaring float float f_val = 10.5; // Declaring int int i_val = 17; // lexical_cast() converts a float into string string strf = boost::lexical_cast(f_val); // lexical_cast() converts a int into string string stri = boost::lexical_cast(i_val); // Displaying string converted numbers cout << "The float value in string is : "; cout << strf << endl; cout << "The int value in string is : "; cout << stri << endl; return 0; }
输出:
The float value in string is : 10.5The int value in string is : 17