C++ C++;Can';t将取消引用的字符指针与字符进行比较

C++ C++;Can';t将取消引用的字符指针与字符进行比较,c++,string,xcode6,C++,String,Xcode6,我有一个输入字符串,我想知道字符串中有多少空格 这是我的密码 // input string std::string str = "abc d e f"; // convert string to cstring char* cstr = new char[str.length()+1]; std::strcpy(cstr, str.c_str()); // iterate through the cstring and count how many spaces are there int

我有一个输入字符串,我想知道字符串中有多少空格

这是我的密码

// input string
std::string str = "abc d e f";

// convert string to cstring
char* cstr = new char[str.length()+1];
std::strcpy(cstr, str.c_str());

// iterate through the cstring and count how many spaces are there
int num_of_spaces = 0;
char* ptr = cstr;

while (ptr) {
    if (*ptr == ' ') {
        ++num_of_spaces;
    }
    ++ptr;
}
但是,我在
if(*ptr='')
行上收到一条错误消息,上面说:
thread1:EXC\u BAD\u ACCESS(code=1,address=0x100200000)


*ptr
不是字符类型的值,因为
ptr
是一个
char*
指针,我将其解引用到
*ptr
。如果是这样,为什么比较是无效的?

你不想要
while(ptr)
,你想要
while(*ptr)
,也就是说,
ptr
指向的不是一个零字符,它标志着一个C风格字符串的结束。

你为什么要把你漂亮的保险箱
字符串
复制到危险的原始内存中?^--那就是。此外,您的循环显示
while(ptr)
,相当于
while(ptr!=NULL)
。您正在递增循环中的指针。你认为
ptr
什么时候会变为空?我想你应该检查
ptr
指向的内容以找到字符串的结尾:
while(ptr)
应该是
while(*ptr)
no?@OliverCharlesworth我可以遍历字符串并将其与“”进行比较,但我只是在学习字符指针。我想知道如果我能用它怎么做pointer@Heisenberg,你最好把时间花在学习如何使用像
std::count
这样的算法上,这样你就不会编写循环来重新创建它们,不管你在迭代什么。哦,显然错误来自无限循环。这解决了所有问题,谢谢!