【C++】静态存储持续性、无链接性

举报
王博Kings 发表于 2020/12/30 00:08:24 2020/12/30
【摘要】 本程序主要关注total,它能够一直记录保持 // static.cpp -- 使用static局部变量#include<iostream>const int ArSize = 10;void strcount(const char * str); int main(){ using namespace std; char input[ArSize]; char next;...

本程序主要关注total,它能够一直记录保持


  
  1. // static.cpp -- 使用static局部变量
  2. #include<iostream>
  3. const int ArSize = 10;
  4. void strcount(const char * str);
  5. int main()
  6. {
  7. using namespace std;
  8. char input[ArSize];
  9. char next;
  10. cout << "输入:\n";
  11. cin.get(input, ArSize);
  12. while (cin)
  13. {
  14. cin.get(next);
  15. while (next != '\n')
  16. {
  17. cin.get(next);
  18. }
  19. strcount(input);
  20. cout << "输入下一行(输入为空时就退出):\n";
  21. cin.get(input, ArSize);
  22. }
  23. cout << "老铁,再见!\n";
  24. return 0;
  25. }
  26. void strcount(const char * str)
  27. {
  28. using namespace std;
  29. static int total = 0;
  30. int count = 0;
  31. cout << "\"" << str << "\" 包含 ";
  32. while (*str++)
  33. {
  34. count++;
  35. }
  36. total += count;
  37. cout << count << "个字符\n";
  38. cout << total << "共这么多\n";
  39. }

运行示例:

输入:
hello
"hello" 包含 5个字符
5共这么多
输入下一行(输入为空时就退出):
my name
"my name" 包含 7个字符
12共这么多
输入下一行(输入为空时就退出):
my name is Jack
"my name i" 包含 9个字符
21共这么多
输入下一行(输入为空时就退出):

每次函数被调用时,自动变量count都将被重置为0。然而,静态变量total只在程序运行时被设置为0,以后在两次函数调用之间,其值将保持不变,因此能够记录读取的字符总数。 

程序解读:

可能这里会有疑问


  
  1. cin.get(next);
  2. while (next != '\n')
  3. {
  4. cin.get(next);
  5. }

 

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

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

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

评论(0

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

全部回复

上滑加载中

设置昵称

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

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

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