C++primer学习日记- - 第3章习题

3.2从标准输入中一次读入一整行。修改程序使其一次读入一个词

#include <iostream>
#include <string>
int main32()
{
 //读入一整行
  using std::string;
  string str;
  while (getline(std::cin, str))
   std::cout << str << std::endl;
   //读入一个词
   std::cin >> str;
 std::cout << str;
   return 0;
   }

3.4读入两个字符串,比较是否相等并输出结果。改写程序,比较字符串长度是否相等。

//比较字符串大小
#include <iostream>
#include <string>
int main()
{
 using std::string;
 using std::cin;
 using std::cout;
 using std::endl;
 string st1, st2;
 cout << "字符串比较" << endl;
 cout << "输入第一个字符串: " <<endl;
 getline(cin, st1);
 cout << "输入第二个字符串: " <<endl;
 getline(cin, st2);
 cout << "第一个字符串: " << st1 << endl;
 cout << "第二个字符串: " << st2 << endl;
 if (st1 == st2)
  cout << "两个字符串相等" << endl;
 else if (st1 >= st2)
  cout << "较大的字符串:" << st1 << endl;
 else
  cout << "较大的字符串:" << st2 << endl;
  return 0;
  }
//比较字符串长度
 #include <iostream>
#include <string>
int main()
{
 using std::string;
 using std::cin;
 using std::cout;
 using std::endl;
 string st1, st2;
 cout << "字符串长度比较" << endl;
 cout << "输入第一个字符串: " << endl;
 getline(cin, st1);
 cout << "输入第二个字符串: " << endl;
 getline(cin, st2);
 cout << "第一个字符串: " << st1 << endl;
 cout << "第二个字符串: " << st2 << endl;
 if (st1.size() == st2.size())
  cout << "两个字符串长度相等" << endl;
 else if (st1.size() >= st2.size())
  cout << "长度较大的字符串:" << st1 << endl;
 else
  cout << "长度较大的字符串:" << st2 << endl;
 return 0;
 }

3.5 字符串拼接

#include <iostream>
#include <string>
int main35()
{
 using std::string;
 using std::cin;
 using std::cout;
 using std::endl;
 string st1, st2;
 getline(cin, st1);
 while (cin >> st2)
  //st1 += st2;//无间隔
  st1 = st1+' ' + st2;//有间隔
 cout << st1<<endl;
 return 0;
 }

3.6 编写一段程序,使用范围for语句将字符串内所有字符用x代替

#include <iostream>
#include <string>
int main36()
{
 using std::string;
 using std::cout;
 using std::cin;
 using std::endl;
 string s;
 while (cin >> s)
  for (char c : s)
   cout << "x";
 cout << endl;
 return 0}

3.10 编写一段程序,读入一个包含标点符号的字符串,将标点符号去掉后输出字符串剩余部分

#include <iostream>
#include <string>
int main()
{
 using std::string;
 using std::cin;
 using std::cout;
 using std::endl;
 string s;
 while (getline(cin, s))
  for (auto c : s)
   if (!ispunct(c))
    cout << c;
 cout << endl;
 return 0;
 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值