【发布时间】:2014-10-13 02:44:08
【问题描述】:
对于我的项目,输入选项之一是“I n”,其中 n 是一个数字。我试图从子字符串中获取“I”的 if 语句中的输入,然后获取最终使用 stringstream 将其转换为整数的数字。
这是我现在的测试代码:
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
cout << "Type in \"I 2\": " << endl;
string in = "";
string numstr = "";
while(in != "Q" && in != "q")
{
cin >> in;
//Input cases
if(in.substr(0,1) == "I")
{
numstr = in.substr(1,1); //numstr is the number in string form
cout << in << "+" << numstr << endl; //I want it to output "I+2"
//but it outputs "I+"
}
else
{
cout << "That was not an option. Try again." << endl;
}
}
return 0;
}
现在的输出是:
I+
That was not an option. Try again.
我可以改变什么让它识别“2”?当我将子字符串更改为 (2,1) 时,我得到一个 out_of_range 异常
【问题讨论】:
-
cin >> in最多读取第一个空白字符。所以,它只是读取'I'。该数字仍在输入流中,等待读取。 -
非常感谢。我已经尝试弄清楚这个程序 8 个小时了,这是困扰我的最后一件事
标签: c++ if-statement input substring substr