通过char迭代字符串char

use*_*385 12 c++

我尝试通过char迭代字符串char.我试过这样的事情:

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

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

h
e
l
l
o
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*nen 24

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

void print(const std::string& infix)
{
    for(auto c : infix)
        std::cout << c << std::endl;
}
Run Code Online (Sandbox Code Playgroud)


Dha*_*dya 14

for(unsigned int i = 0; i<infix.length(); i++) {
    char c = infix[i]; //this is your character
}
Run Code Online (Sandbox Code Playgroud)

这就是我做到的.不确定这是不是"惯用".


0x4*_*2D2 6

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

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

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