c++ - C++:将字符串或字符转换为 int
问题描述
如果我有:
string number = "45";
我如何"45"
变成45
整数?
我希望能够做到这一点:
string number + 20 = 65
解决方案
您可以使用https://en.cppreference.com/w/cpp/string/basic_string/stol中的以下示例:
#include <iostream>
#include <string>
int main()
{
std::string str1 = "45";
std::string str2 = "3.14159";
std::string str3 = "31337 with words";
std::string str4 = "words and 2";
int myint1 = std::stoi(str1);
int myint2 = std::stoi(str2);
int myint3 = std::stoi(str3);
// error: 'std::invalid_argument'
// int myint4 = std::stoi(str4);
std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';
std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';
std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';
//std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';
}
推荐阅读
- c++ - 优先队列构造函数的作用
- computer-science - 如何设计 NPDA 来接受这些语言?
- javascript - JavaScript - 导入后 (webmix) 未捕获 ReferenceError: getJobData is not defined 错误
- node.js - 是否可以在控制台中一键重启我的 DIScordBot?
- python - 如何将列表文本中的数字与字母分开
- python-3.x - 分离 Tkinter GUI 和应用程序的控制
- java - 如何对 API 进行单元测试?
- powershell - Powershell全局变量权限问题 - 需要重写帮助
- google-cloud-platform - gcloud CLI 的分段错误
- python - Tkinter 破坏 Toplevel 并创建另一个错误