无法将字符串类型转换为bool c ++

时间:2014-03-31 17:55:17

标签: c++ string boolean type-conversion

我从教程中编写了这段代码来学习toupper函数,但是在运行时,我得到了while语句的编译时错误cannot convert string type to bool。还有另一种方法可以解决这个问题吗?

#include <iostream>
#include <cctype>
#include <stdio.h>

using namespace std;

char toupper(char numb);

int main()
{
    char c;

    int w = 0;
    string anArray[] = {"hello world"};

    while (anArray[w])
    {
        c = anArray[w];

        putchar (toupper(c));
        w++;

    }
}

2 个答案:

答案 0 :(得分:4)

只需使用实际的string类型即可。这是C ++而不是C。

string anActualString = "hello strings";

您混淆了在C中实现字符串所需的经典字符数组以及在C ++中使用实际字符串的能力。

此外,您无法执行while (anArray[w])因为while()测试布尔值为true或false。 anArray[w]是一个字符串,而不是布尔值truefalse。此外,你应该意识到anArray只是一个大小为1的字符串数组,就像你发布它一样。这样做:

int w = 0;
string aString = "hello world";

while (w < aString.length()) // continue until w reaches the length of the string
{
    aString[w] = toupper(aString[w]);
    w++;
}

C ++中关于字符串的巧妙之处在于,您可以在它们上使用[],就好像它们是常规数组一样。

答案 1 :(得分:0)

示例看起来可能想要输入

char anArray[] = { "hello world" };

char anArray[] = "hello world";

而不是原来的

string anArray[] = { "hello world" };

就像Adosi已经指出的那样,std :: string是一种更像c ++的方法。

相关问题