简体   繁体   English

输出混乱

[英]Output confusion

Shouldn't the output be: Heo Word? 输出不应该是:Heo Word? as it will print the letter as long as they aren't 'l', but the output I get is: eo World? 只要它不是'l',它将打印字母,但是我得到的输出是:eo World?

   #include <iostream> 
   using namespace std; 
   int main() {  
       char str[] = "Hello World\n";  
       char* p = str;   
       while ( *p++ ) {
           if ( *p != 'l' )       
               cout << *p;
       } 
   }

The code in the while loop condition already increments the pointer value while循环条件中的代码已经增加了指针值

while ( *p++ )

thus the check inside the loops scope 因此在循环范围内进行检查

if ( *p != 'l' )

always misses the 1st character. 总是错过第一个字符。

The easiest and most comprehensible way to rewrite this loop is probably 重写此循环的最简单,最易理解的方法可能是

 char str[] = "Hello World\n";  
 for (char*p = str; *p; ++p) {
     if ( *p != 'l' )       
         cout << *p;
 } 

Working online example . 在线工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM