【C++ Primer】(第5版) 练习3.6 编写一段程序,使用范围for语句将字符串内的所有字符用X代替。

mac2026-05-21  4

C++ Primer 第5版 P86 练习3.6 编写一段程序,使用范围for语句将字符串内的所有字符用X代替。

#include<iostream> #include<string> #include<random> #include<chrono> using std::string; using std::cin; using std::cout; using std::endl; std::uniform_int_distribution<unsigned> u(1, 100); std::uniform_int_distribution<short> c(32, 126); //随机均匀整数分布 std::default_random_engine d; //随机引擎 string s; unsigned n; void main() { std::ios::sync_with_stdio(false); cin.tie(0);//关闭与 stdio 的同步,解除 cin 与 cout 的绑定,加快输入输出速率 d.seed(std::chrono::steady_clock::now().time_since_epoch().count());//利用当前系统时间作为随机引擎的种子 for (;;) { s.clear(); n = u(d);//随机指定字符串的长度为 1 ~ 100 for (unsigned i = 0; i < n; ++i)s += c(d);//随机生成 ASCII 范围为离散闭区间 [32, 126] 的可见字符及空格,长度为 n cout << "原字符串:\n\n" << s << "\n\n正在将全部字符换成 'X'...\n\n"; for (unsigned i = 0; i < n; ++i)s[i] = 'X'; cout << "替换完毕\n\n" << s << '\n' << endl; system("pause"); } }
最新回复(0)