C++ 如何将字符串转换为三个整数
我正在尝试将一个字符串转换成三个整数。我需要用“11”、“5”和“2”做一些数学题。至少在这个例子中。我尝试使用stoi()将字符串转换为整数,但我无法完成仅获取字符串一部分的部分,如下面的第二个示例所示。有没有简单的解决办法?本周我开始用C++编程,所以我没有太多的知识。C++ 如何将字符串转换为三个整数,c++,string,integer,C++,String,Integer,我正在尝试将一个字符串转换成三个整数。我需要用“11”、“5”和“2”做一些数学题。至少在这个例子中。我尝试使用stoi()将字符串转换为整数,但我无法完成仅获取字符串一部分的部分,如下面的第二个示例所示。有没有简单的解决办法?本周我开始用C++编程,所以我没有太多的知识。 #include <iostream> #include <cmath> #include <string> #include <sstream> using namespac
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
using namespace std;
int main() {
int seconds 01 = 0;
int seconds 10 = 0; // somehow either one was beeing set to 35 by default, so I had to do
this
int minutes = 0;
string time = "11:52"; // mm:ss format
// I need to convert the string into three integers
cout << minutes << " " << seconds10 " " << seconds01;
return 0;
}
功能:
string time = "01:50"; // mm:ss format
int seconds10 = stoi(time[3]);
// [Error] call of overloaded 'stoi(char&)' is ambiguous
会议记录应输出“11”秒10=5
seconds01=2
stoi(时间[3])
将不起作用,因为这是将单个char
传递给stoi()
,它需要一个以null结尾的char*
字符串。您可以改用stoi(&time[3])
(因为string
的内部缓冲区在C++11及更高版本中保证以null结尾),或者更好的stoi(time.C_str()+3)
,例如:
string time=“01:50”//mm:ss格式
int seconds=stoi(time.c_str()+3);
int seconds10=秒/10;
int seconds01=秒%10;
否则,可以通过string::find()
和string::substr()
将std::string
拆分为所需的子字符串,然后可以将子字符串转换为整数,例如:
string time=“11:52”//mm:ss格式
auto pos=time.find(“:”);
int minutes=stoi(time.substr(0,pos));
int seconds=stoi(time.substr(pos+1));
int seconds10=秒/10;
int seconds01=秒%10;
或者,您可以将std::string
放入std::istringstream
中,然后使用operator>
从中提取值,例如:
string time=“11:52”//mm:ss格式
整数分,秒;
半结肠;
istringstream iss(时间);
iss>>分钟>>冒号>>秒;
int seconds10=秒/10;
int seconds01=秒%10;
也就是说,您也可以像这样提取seconds10
和seconds01
值(参见),例如:
string time=“11:52”//mm:ss格式
整数分钟,秒10,秒01;
整数分钟=。。。;
int seconds10=时间[3]-“0”;
int seconds01=时间[4]-“0”;
问题的第一部分:拆分字符串
#包括
#包括
#包括
使用名称空间std;
int main(){
string time=“11:52”//mm:ss格式
int pos=time.find(“:”);
int minutes=stoi(time.substr(0,pos));
int seconds=stoi(time.substr(位置5));
cout您还可以创建这样一个函数,用于拆分字符串并将其转换为向量
#包括
#包括
#包括
#包括
std::vector to_int(std::string const&s,char delim)
{
std::向量结果;
标准:istringstream iss;
字符串标记;
while(std::getline(iss、token、delim))
结果:推回(std::stoi(令牌));
返回结果;
}
int main()
{
字符串str{“01:50:34:2341”};
自动整数=到整数(str,,:');
用于(自动编号:ints)
{
std::cout@RemyLebeau你能举个例子吗,我不明白你想说什么如果在VS或gcc/clang和-Wall-Wextra-pedantic-Wshadow上,我会警告你,并修复所有警告。因为你在最后两个数字上操作int seconds10=time[3]-'0';
可能足够。time.substr(pos,5)
是错误的。pos
保存的索引:
,第二个参数是计数而不是索引。它需要是time.substr(pos+1,2)
,或者只是time.substr(pos+1)
谢谢最后两个解决方案非常好。我不完全理解它们,但现在我对此没有意见。谢谢
1
50
34
2341