在while循环中增加*char的指针

Bbv*_*ghe 5 c++ string pointers loops traversal

这是我有的:

char* input = new char [input_max]
char* inputPtr = iput;
Run Code Online (Sandbox Code Playgroud)

我想使用inputPtr遍历输入数组.但是我不确定什么会正确检查我是否到达了字符串的末尾:

while (*inputPtr++)
{
    // Some code
}
Run Code Online (Sandbox Code Playgroud)

要么

while (*inputPtr != '\0')
{
    inputPtr++;
    // Some code
}
Run Code Online (Sandbox Code Playgroud)

还是更优雅的选择?

gre*_*olf 9

假设输入字符串以空值终止:

for(char *inputPtr = input; *inputPtr; ++inputPtr)
{
  // some code
}
Run Code Online (Sandbox Code Playgroud)

请记住,您发布的示例可能无法提供您想要的结果.在while循环条件下,您始终执行后增量.当你进入循环时,你已经传递了第一个角色.举个例子:

#include <iostream>
using namespace std;

int main()
{
  const char *str = "apple\0";
  const char *it = str;
  while(*it++)
  {
    cout << *it << '_';
  }
}
Run Code Online (Sandbox Code Playgroud)

这输出:

p_p_l_e__

注意最后丢失的第一个字符和额外的_下划线.如果您对预增量和后增量运算符感到困惑,请查看此相关问题.