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;
}