C ++我无法将char变量与值进行比较

时间:2015-01-23 21:59:28

标签: c++ char comparison

我必须参加第一个cs课程。它是一个基本的计算器,它接受一个运算符和一个值并计算总数(总计从0开始)。

#include <iostream>

using namespace std;

int main()
{
    char oprtr;
    float value, total = 0.0;

    cin >> oprtr >> value;

    while (oprtr != "q")
    {
        if (oprtr == "+")
            total += value;
        else if (oprtr == "-")
            total -= value;
    }
}

它还没有完成,但已经遇到了问题。它会出现错误,说明&#34;禁止将char值与int值进行比较&#34;

4 个答案:

答案 0 :(得分:10)

双引号("q")用于字符串。单引号('q')用于字符。

所以:

while (oprtr != 'q')
{
    if (oprtr == '+')
        total += value;
    else if (oprtr == '-')
        total -= value;
}

答案 1 :(得分:1)

Char表示Character,您必须使用单引号'',双引号""表示字符串。

您收到此错误的原因是您尝试将字符与字符串文字(const char)进行比较,您得到的确切错误将是:

  

操作数类型不兼容(“char”和“const char”)。

以下代码将修复此错误:

#include <iostream>

using namespace std;

int main()
{
    char oprtr;
    float value, total = 0.0;

    cin >> oprtr >> value;

    while (oprtr != 'q')
    {
        if (oprtr == '+')
            total += value;
        else if (oprtr == '-')
            total -= value;
    }
}

答案 2 :(得分:1)

而且,由于您正在阅读语句或表达式一次,因此当角色不等于&#39; q&#39;时,您无需循环。你基本上应该执行一个操作。此外,switch是一个非常有用的结构,用于比较文字而不是几个if。所以我会把它简化为。

{{1}}

这基本上读入一个表达式并将其添加到总计中。您可以根据需要将其修改为读取。

答案 3 :(得分:-3)

比较字符串长度是C编程中的常用功能,因为它允许您查看哪个字符串包含更多字符。这对于排序数据非常有用。比较字符串需要一个特殊的功能;不要使用!=或==。

http://www.techonthenet.com/c_language/standard_library_functions/string_h/strcmp.php