mad*_*eer 3 c++ string int std type-conversion
编辑:此问题已被标记为重复.我确实查看了以前所有类似的问题,但我找不到答案.基本上,我无法控制程序的编译方式(虽然我认为它已经在使用c ++ 11),所以我要么找到为什么stoi不能在这种情况下工作的原因或任何可以服务的替代语句同样的目的.
我是c ++的新手,正在为这个项目上课.它必须通过myprogramminglab.com提交,所以我无法修改编译器.我遇到的问题是我收到以下错误:
CTest.cpp: In function 'void getTime(int&, int&, bool&, std::string)':
CTest.cpp:38: error: 'stoi' is not a member of 'std'
CTest.cpp:39: error: 'stoi' is not a member of 'std'
Run Code Online (Sandbox Code Playgroud)
我从谷歌上了解到,这通常意味着我的编译器没有配置为C++ 11.但就像我说的那样,我无法控制myprogramminglab的那个方面.我错过了我的代码中可能能够启动并运行的东西.或者如果没有,是否有一种"老"方式可以使用我可以使用的方法?我在书中找不到一个好的解决方案(虽然我承认我可能只是不知道该寻找什么)并且在我遇到这个编译错误之前无法测试其余的代码.
如果从代码中看不明显,则以HH:MM xm格式输入它,并计算两次之间的分钟数,并输出该差异的分钟(以及小时和分钟)的数量.我还必须使用一个名为computeDifference的函数和所提到的参数(虽然我添加了字符串参数,因为我想获取函数之外的输入).
#include <iostream>
#include <string>
using namespace std;
int computeDifference(int hours_par, int minutes_par, bool isAM_par, int hoursF_par, int minutesF_par, bool isAMF_par);
void getTime(int& minutes, int& hours, bool& isAM);
int main()
{
int hours, minutes, fut_hours, fut_minutes, difference;
bool isAM, fut_isAM;
cout << "Enter start time, in the format 'HH:MM xm', where 'xm' is\n";
cout << "either 'am' or 'pm' for AM or PM:";
getTime(hours, minutes, isAM);
cout << "Enter future time, in the format 'HH:MM xm', where 'xm' is\n";
cout << "either 'am' or 'pm' for AM or PM:";
getTime(fut_hours, fut_minutes, fut_isAM);
difference = computeDifference(hours, minutes, isAM, fut_hours, fut_minutes, fut_isAM);
cout << "There are " << difference << " minutes (" << (difference - (difference%60))/60 << " hours and " << difference%60 << " minutes) between" << hours << ":" << minutes<< " and " << fut_hours << ":" << fut_minutes;
return 0;
}
int computeDifference(int hours_par, int minutes_par, bool isAM_par, int hoursF_par, int minutesF_par, bool isAMF_par) {
int start_total = 0, future_total = 0;
start_total += hours_par * 60;
start_total += minutes_par;
if (isAM_par)
start_total += 720;
future_total += hoursF_par * 60;
future_total += minutesF_par;
if (isAMF_par)
future_total += 720;
return future_total - start_total;
}
void getTime(int& minutes, int& hours, bool& isAM, string timestamp) {
string hoursS, minutesS;
hoursS = timestamp.substr(0, 2);
minutesS = timestamp.substr(3, 2);
hours = std::stoi(hoursS);
minutes = std::stoi(minutesS);
isAM = ("am" == timestamp.substr(6, 2));
cout << hours << " " << minutes << " " << isAM;
cout << timestamp;
}
Run Code Online (Sandbox Code Playgroud)
我尝试了几种不同的方式,例如没有std :: part.但这似乎给我最少的错误......
任何帮助将不胜感激!谢谢!
std::stoi是c ++ 11提供的函数,因此-std=c++11 如果您有C++ 11可用编译器,请提供编译器选项
否则使用atoi()代替stoi()如下:
#include<cstdlib>
hours = std::atoi(hoursS.c_str());
minutes = std::atoi(minutesS.c_str());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11249 次 |
| 最近记录: |