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

it2022-05-05  167

本程序主要关注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); }

 

人工智能博士 认证博客专家 985AI博士 AI专家 博客专家 王博Kings,985AI博士在读,博客专家,华为云专家,是《机器学习手推笔记》、《深度学习手推笔记》等作者,我的微信:Kingsplusa,欢迎交流学习;在人工智能、计算机视觉、无人驾驶等具有丰富的经验。

最新回复(0)