简体   繁体   English

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

[英]cannot convert string type to bool c++

I wrote this code from a tutorial to learn the toupper function, but when ran I get a compile time error cannot convert string type to bool for the while statement. 我是从教程中编写此代码来学习toupper函数的,但是运行时出现编译时错误cannot convert string type to bool while语句的cannot convert string type to bool Is there another way to approach this? 还有另一种方法可以解决这个问题吗?

#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++;

    }
}

Just use the actual string type. 只需使用实际的string类型。 This is C++ not C. 这是C ++而不是C。

string anActualString = "hello strings";

You're confusing the classic array of characters necessary to implement strings in C and the ability to use actual strings in C++. 您混淆了在C中实现字符串和在C ++中使用实际字符串的能力所需的经典字符数组

Also, you cannot do while (anArray[w]) because the while() tests for boolean true or false. 另外,您不能执行while (anArray[w])因为while()测试的是布尔值true还是false。 anArray[w] is a string, not a boolean true or false . anArray[w]是一个字符串,不是布尔值truefalse Also, you should realize that anArray is just a string array of size 1, the way you posted it. 同样,您应该意识到anArray只是大小为1的字符串数组,就像您发布它的方式一样。 Do this instead: 改为这样做:

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++;
}

The neat thing about strings in C++ is that you can use the [] on them as if they were regular arrays. 关于C ++中字符串的整洁之处在于,您可以在它们上使用[] ,就好像它们是常规数组一样。

The sample looks as they might have wanted to type 该样本看起来像他们可能想要键入的

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

or 要么

char anArray[] = "hello world";

instead of the original 而不是原始的

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

Like Adosi already pointed out, std::string is a more c++ like approach. 就像Adosi已经指出的那样,std :: string是一种更像c ++的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM