TheStache
TheStache

Reputation: 39

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

    }
}

Upvotes: 0

Views: 1841

Answers (2)

Omar Himada
Omar Himada

Reputation: 2588

Just use the actual string type. This is C++ not 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++.

Also, you cannot do while (anArray[w]) because the while() tests for boolean true or false. anArray[w] is a string, not a boolean true or false. Also, you should realize that anArray is just a string array of size 1, the way you posted it. 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.

Upvotes: 4

wonko realtime
wonko realtime

Reputation: 565

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.

Upvotes: 0

Related Questions