2014-03-31 49 views
0

我从教程中编写了该代码以了解toupper函数,但运行时,while语句的编译时错误cannot convert string type to bool。有另一种方法来解决这个问题吗?无法将字符串类型转换为bool C++

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

    } 
} 

回答

4

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

string anActualString = "hello strings";

你混淆了经典字符数组必要的,以实现在C字符串,并在C使用的实际 ++的能力。

此外,你不能做while (anArray[w])因为while()测试布尔真或假。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++字符串的整洁的事情是,你可以对他们使用[],好像他们是普通阵列。

+0

实际上,anArray [w]是原始文章中的一个字符串。 anArray初始化为大小为1的字符串数组。因此,anArray [0]是字符串,并且anArray [1]超出数组末尾。 – Steger

+0

所以在c中他们使用的数组主要是一系列数字或字符。现在在C++中,他们演变为字符串 – TheStache

+0

@Adosi:你可以编辑你的答案纠正它有关anArray [w]?可能应该这样说:“anArray [0]是字符串...” – Steger

0

样品看起来他们也许是想键入

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

char anArray[] = "hello world"; 

代替了原来的

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

像Adosi已经指出的那样,的std :: string是一个更类似C++的方法。

相关问题