16

我尝试逐个字符地遍历字符串字符。我试过这样的事情:

void print(const string& infix)
{
char &exp = infix.c_str();
while(&exp!='\0')
{
         cout<< &exp++ << endl;
    }
}

所以这个函数调用 print("hello"); 应该返回:

h
e
l
l
o

我尝试使用我的代码,但它根本不起作用。顺便说一句,参数是引用而不是指针。谢谢

4

4 回答 4

28

您的代码需要一个指针,而不是引用,但如果使用 C++11 编译器,您只需要:

void print(const std::string& infix)
{
    for(auto c : infix)
        std::cout << c << std::endl;
}
于 2013-02-03T01:19:37.070 回答
15
for(unsigned int i = 0; i<infix.length(); i++) {
    char c = infix[i]; //this is your character
}

我就是这样做的。不确定这是否太“惯用”。

于 2013-02-03T00:53:35.610 回答
6

如果您正在使用std::string,则确实没有理由这样做。您可以使用迭代器:

for (auto i = inflix.begin(); i != inflix.end(); ++i) std::cout << *i << '\n';

至于您应该使用的原始代码,char*而不是char您不需要参考。

于 2013-02-03T00:54:45.040 回答
0

std::string::c_str()返回const char*,你不能char&用来持有它。exp 也是指针,你不需要参考:

最好使用迭代器:

void print(const string& infix)
{
  for (auto c = infix.begin(); c!=infix.end(); ++c)
  {
    std::cout << *c << "\n";
  }
  std::cout << std::endl;
}

要修复您的原始代码,请尝试:

void print(const string& infix)
{
  const char *exp = infix.c_str();
  while(*exp!='\0')
  {
    cout << *exp << endl;
    exp++;
   }
 }
于 2013-02-03T00:54:17.533 回答