C++字符串,该字符串不能包含加号

C++ strings, the string cant contain the plus sign

本文关键字:字符串 包含加 不能 C++      更新时间:2023-10-16

我正在尝试制作一个更高级的计算器,您可以在其中输入一段代数。我有这个问题,包含你输入的字符串的'+'测试结果不呈阳性,即使它呈阳性。

这是测试字符串的代码

for(int i = 0; i < line.length(); i++)
{
    if(pos == 0 && line[i] >= '0' && line[i] <= '9' || line[i] == '.')
    {           
        p1[p1p] = line[i]; // setting the number to the current character
        p1p++; // position of the first number  
    }
    if(line[i] == '+')
    {
    pos++; 
    operation = 1;
    cout << "add" << endl;
    }
}

除非数字的最后一个字符和+符号之间没有空格,否则它永远不会输出+

例如,"100+10"的"+"检测结果为阳性但"100+10"不会。

谢谢-Hugh

如果我的猜测是正确的,则使用std::cin输入数据。这就是为什么它不读取第一空白之后的字符。

请改用getline()函数。

您可以使用operator>>,它自然读取(可选)空格分隔的值。

int val;
while(std::cin >> val)
{
    // We have a value (an integer)
    char c;
    if (std::cin >> c)
    {
        // we have read the next non space character
        switch(c)
        {
            case '+': std::cout << "Adding: " << val << "n";break;
        }
    }
}