当你使用 C++ 进行编码时,经常会需要将一种数据类型转换为另一种数据类型。
在本文中,你将通过查看两种最常用的方法来学习如何在 C++ 中将字符串转换为整数。
让我们开始吧!
C++ 中的数据类型
C++ 编程语言有一些内置的数据类型:
int
,用于整数(例如 10、150)double
,用于浮点数(例如 5.0、4.5)char
,用于单个字符(例如 “D”、“!”)string
,用于字符序列(例如 “Hello”)bool
,用于布尔值(真或假)
C++ 是一种强类型编程语言,这意味着当你创建一个变量时,你必须明确声明将在其中存储什么类型的值。
如何在 C++ 中声明和初始化 int
要在 C++ 中声明一个 int
变量,你需要首先编写变量的数据类型——在本例中为 int
。这将让编译器知道变量可以存储什么样的值,从而知道它可以采取什么行动。
接下来,你需要为变量命名。
最后,不要忘记用分号结束语句!
#include <iostream>
int main() {
int age;
}
然后,你可以为你创建的变量赋值,如下所示:
#include <iostream>
int main() {
int age;
age = 28;
}
你可以通过初始化变量并最终打印结果来组合它们,而不是将这些操作作为单独的步骤执行:
// a header file that enables the use of functions for outputing information
//e.g. cout or inputing information e.g. cin
#include <iostream>
// a namespace statement; you won't have to use the std:: prefix
using namespace std;
int main() { // start of main function of the program
int age = 28;
// initialize a variable.
//Initializing is providing the type,name and value of the varibale in one go.
// output to the console: "My age is 28",using chaining, <<
cout << "My age is: " << age << endl;
}// end the main function
如何在 C++ 中声明和初始化 string
字符串是单个字符的集合。
在 C++ 中声明字符串的工作方式与声明和初始化整数非常相似,你在上一节中看到了这一点。
C++ 标准库提供了一个字符串类。为了使用字符串数据类型,你必须在文件顶部的 #include <iostream>
之后包含 <string>
库。
包含该头文件后,你还可以添加你之前看到的 using namespace std;
。
除此之外,在添加这一行之后,你在创建字符串变量时将不必使用 std::string
——只需单独使用 string
即可。
#include <iostream>
#include <string>
using namespace std;
int main() {
//declare a string variable
string greeting;
greeting = "Hello";
//the `=` is the assignment operator,assigning the value to the variable
}
或者你可以初始化一个字符串变量,并将其打印到控制台:
#include <iostream>
#include <string>
using namespace std;
int main() {
//initialize a string variable
string greeting = "Hello";
//output "Hello" to the console
cout << greeting << endl;
}
如何将字符串转换为整数
如前所述,C++ 是一种强类型语言。
如果你尝试提供与数据类型不一致的值,你将收到错误消息。
此外,将字符串转换为整数并不像使用类型转换那么简单,你可以在将 double
转换为 int
时使用它。
例如,你不能这样做:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "7";
int num;
num = (int) str;
}
编译后的错误将是:
hellp.cpp:9:10: error: no matching conversion for C-style cast from 'std::__1::string' (aka
'basic_string<char, char_traits<char>, allocator<char> >') to 'int'
num = (int) str;
^~~~~~~~~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/string:875:5: note: candidate function
operator __self_view() const _NOEXCEPT { return __self_view(data(), size()); }
^
1 error generated.
有几种方法可以将字符串转换为 int,您将在接下来的部分中看到其中提到的两种方法。
如何使用 stoi()
函数将字符串转换为 int
将字符串对象转换为数字 int
的一种有效方法是使用 stoi()
函数。
此方法通常用于较新版本的 C++,在 C++11 中引入。
它接受一个字符串值作为输入,并返回它的整数版本作为输出。
#include <iostream>
#include <string>
using namespace std;
int main() {
// a string variable named str
string str = "7";
//print to the console
cout << "I am a string " << str << endl;
//convert the string str variable to have an int value
//place the new value in a new variable that holds int values, named num
int num = stoi(str);
//print to the console
cout << "I am an int " << num << endl;
}
输出:
I am a string 7
I am an int 7
如何使用 stringstream
类将字符串转换为 int
stringstream
类主要用于早期版本的 C++。它通过对字符串执行输入和输出来工作。
要使用它,你首先必须通过添加 #include <sstream>
行在程序顶部包含 sstream
库。
然后添加 stringstream
并创建一个 stringstream
对象,该对象将保存要转换为 int 的字符串的值,并将在将其转换为 int 的过程中使用。
你可以使用 <<
运算符从字符串变量中提取字符串。
最后,你使用 >>
运算符将新转换的 int 值输入到 int 变量中。
#include <iostream>
#include <string>
#include <sstream> // this will allow you to use stringstream in your program
using namespace std;
int main() {
//create a stringstream object, to input/output strings
stringstream ss;
// a variable named str, that is of string data type
string str = "7";
// a variable named num, that is of int data type
int num;
//extract the string from the str variable (input the string in the stream)
ss << str;
// place the converted value to the int variable
ss >> num;
//print to the consloe
cout << num << endl; // prints the intiger value 7
}
总结
你已经看到了在 C++ 中将字符串转换为整数的两种简单方法。
如果你想了解有关 C++ 编程语言的更多信息,请查看 freeCodeCamp 的 4 小时的视频教程。
感谢阅读,祝你学习愉快😊
原文:String to Int in C++ – How to Convert a String to an Integer Example,作者:Dionysia Lemonaki