【C++】静态存储持续性、无链接性
【摘要】 本程序主要关注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,它能够一直记录保持
-
// static.cpp -- 使用static局部变量
-
#include<iostream>
-
const int ArSize = 10;
-
void strcount(const char * str);
-
-
int main()
-
{
-
using namespace std;
-
char input[ArSize];
-
char next;
-
-
cout << "输入:\n";
-
cin.get(input, ArSize);
-
while (cin)
-
{
-
cin.get(next);
-
while (next != '\n')
-
{
-
cin.get(next);
-
}
-
strcount(input);
-
cout << "输入下一行(输入为空时就退出):\n";
-
cin.get(input, ArSize);
-
}
-
cout << "老铁,再见!\n";
-
return 0;
-
}
-
-
void strcount(const char * str)
-
{
-
using namespace std;
-
static int total = 0;
-
int count = 0;
-
-
cout << "\"" << str << "\" 包含 ";
-
while (*str++)
-
{
-
count++;
-
}
-
total += count;
-
cout << count << "个字符\n";
-
cout << total << "共这么多\n";
-
}
运行示例:
输入:
hello
"hello" 包含 5个字符
5共这么多
输入下一行(输入为空时就退出):
my name
"my name" 包含 7个字符
12共这么多
输入下一行(输入为空时就退出):
my name is Jack
"my name i" 包含 9个字符
21共这么多
输入下一行(输入为空时就退出):
每次函数被调用时,自动变量count都将被重置为0。然而,静态变量total只在程序运行时被设置为0,以后在两次函数调用之间,其值将保持不变,因此能够记录读取的字符总数。
程序解读:
可能这里会有疑问
-
cin.get(next);
-
while (next != '\n')
-
{
-
cin.get(next);
-
}
文章来源: kings.blog.csdn.net,作者:人工智能博士,版权归原作者所有,如需转载,请联系作者。
原文链接:kings.blog.csdn.net/article/details/96432612
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)