接受坐标,但是向量中插入了错误的值?

时间:2013-05-30 11:41:41

标签: vector

我正在解析用户的坐标,我想将它们添加到一个向量中(不确定将采用多少个)。但是,插入了错误的值。如图所示:

string userInput;
getline(cin,userInput);

for(int i = 0; i < userInput.length(); i++)
{
    if(isdigit(userInput[i]))
    {
        results.push_back(userInput[i]);
        if(isdigit(userInput[i + 1])) //check the value next to it too (max of double digits)
        {
            results[i] = 10 * (userInput[i + 1]); //add it to the vale
        }
    }
}

如果我输入(1,2) - (3,4),'('被跳过,但由于某种原因,当它看到1是一个数字时,它将49放入向量以及其他随机任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:1)

userInput[i]char类型。它不是随机的,而是用ASCII编码的。 ASCII中的'0'...'9'以十进制48-57编码。因此,您可以使用userInput[i] - 48userInput[i] - '0'获取您的int。

代码中的另一个问题:在每次迭代中,你检查它旁边的值,但是在下一次迭代中不会跳过它,这意味着如果输入是1234,你将得到一个向量{{ 1}}

另一个问题是:您的代码永远不会捕获3位数字。

最后(希望如此),您的{12,23,34}会丢弃您的第一个数字。

BTW,为什么不使用results[i] = 10 * (userInput[i + 1])来解析你的输入?以下函数将解析一个坐标。

stringstream