【C++】针对char 字符类型cout的三种输出情况(++ch 和 ch+1 和 ch++)难点加重点

举报
王博Kings 发表于 2020/12/30 00:59:36 2020/12/30
【摘要】 1.++ch,代表字符+1输出,比如输入是a,那么输出是b #include<iostream>using namespace std;int main(){ char ch; cout << "输入,我将重复\n"; cin.get(ch); while (ch != '.') { if (ch == '\n') cout << ch; else cout ...

1.++ch,代表字符+1输出,比如输入是a,那么输出是b


  
  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. char ch;
  6. cout << "输入,我将重复\n";
  7. cin.get(ch);
  8. while (ch != '.')
  9. {
  10. if (ch == '\n')
  11. cout << ch;
  12. else
  13. cout << ++ch;//将ch往后加1输出字符
  14. cin.get(ch);
  15. }
  16. cout <<"OK"<< endl;
  17. system("pause");
  18. return 0;
  19. }

运行结果:

2.ch+1,代表字符+1后ASCII输出,比如输入是a,那么输出是98


  
  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. char ch;
  6. cout << "输入,我将重复\n";
  7. cin.get(ch);
  8. while (ch != '.')
  9. {
  10. if (ch == '\n')
  11. cout << ch;
  12. else
  13. cout << ch+1;
  14. cin.get(ch);
  15. }
  16. cout <<"OK"<< endl;
  17. system("pause");
  18. return 0;
  19. }

运行结果:

当然如果想输出原始ASCII值,可以ch+1-1,但是这样不如int(ch)方便

3.ch++,代表字符先输出,后加1,所以输入abc,输出还是abc


  
  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. char ch;
  6. cout << "输入,我将重复\n";
  7. cin.get(ch);
  8. while (ch != '.')
  9. {
  10. if (ch == '\n')
  11. cout << ch;
  12. else
  13. cout << ch++;
  14. cin.get(ch);
  15. }
  16. cout <<"OK"<< endl;
  17. system("pause");
  18. return 0;
  19. }

 运行结果

有人问,那ch++没有任何作用吗?

回答是否定的!肯定有作用,我们加一句cout输出语句


  
  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. char ch;
  6. cout << "输入,我将重复\n";
  7. cin.get(ch);
  8. while (ch != '.')
  9. {
  10. if (ch == '\n')
  11. cout << ch;
  12. else
  13. cout << ch++;
  14. cout << " ch++ " << ch <<endl;
  15. cin.get(ch);
  16. }
  17. cout <<"OK"<< endl;
  18. system("pause");
  19. return 0;
  20. }

文章来源: kings.blog.csdn.net,作者:人工智能博士,版权归原作者所有,如需转载,请联系作者。

原文链接:kings.blog.csdn.net/article/details/84578545

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。