4.std::string中库函数的使用。
2024-09-01 16:10:33
为了美观,我们把输入和输出设计成如下:
#include <iostream>
#include <string> int main()
{ std::string name;
std::string s3,s2;
std::cout << "Please enter your first name: ";
std::cin >> name;
s3 = "* Hello, " + name + "! *" ;
std::string s1(s3.size(), '*');
std::string spaces(s3.size() - , ' ');
s2 = "*" + spaces + "*";
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
std::cout << s3 << std::endl;
std::cout << s2 << std::endl;
std::cout << s1 << std::endl;
system("pause");
return ;
}
这里运用到的方法:
1.string的构造函数 string(int size, char ch)。指定字符串的长度,字符串中所有字符设置为ch。
2.string::size()函数返回字符串的长度,不包含'\0'。
3.string类中重载了 + 号。 直接 "something" + string 返回string类型。
课后习题:
1)下面的声明有效吗?
const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";
有效。
2)下面的程序正确吗?
#include <iostream>
#include <string> int main()
{
{ const std::string s = "a string";
std::cout << s << std::endl; } { const std::string s = "another string";
std::cout << s << std::endl; }
return ;
}
正确。 {}里面声明的变量,范围就是声明它的{}。所以可以在两个不同的{}{}中声明名称一样的变量。
3)下面的程序输出正确吗?
#include <iostream>
#include <string> int main()
{
{ const std::string s = "a string";
std::cout << s << std::endl;
{ const std::string s = "another string";
std::cout << s << std::endl; }}
return ;
}
正确。输出和上一个程序一样。不同的是。在第二个{}里面。声明的s变量,覆盖了外部声明的s变量。
把倒数第三行的}}改成};}程序输出正确吗?
#include <iostream>
#include <string> int main()
{ { const std::string s = "a string";
std::cout << s << std::endl;
{ const std::string s = "another string";
std::cout << s << std::endl; };} system("pause");
return ;
}
正确。和上一个例子不同的在于,第一个{}里面多了一个;的空白语句。
4)下面的程序正确吗?
#include <iostream>
#include <string> int main()
{
{ std::string s = "a string";
{ std::string x = s + ", really";
std::cout << s << std::endl; }
std::cout << x << std::endl;
}
return ;
}
不正确。x声明在第二个{}范围了。出了第二个{}范围,就不知道x是什么了。
修改如下,把x的声明放在第一个{}里面
int main()
{ { std::string s = "a string";
std::string x;
{ x = s + ", really";
std::cout << s << std::endl; }
std::cout << x << std::endl;
} system("pause");
return ;
}
5)下面程序输入 Samuel Beckett 预测输出?
#include <iostream>
#include <string> int main()
{ std::cout << "What is your name? ";
std::string name;
std::cin >> name;
std::cout << "Hello, " << name
<< std::endl << "And what is yours? ";
std::cin >> name;
std::cout << "Hello, " << name
<< "; nice to meet you too!" << std::endl; system("pause");
return ;
}
输入Samuel Beckett
输出:
What is your name? Samuel Beckett
Hello, Samuel
And what is yours? Hello, Beckett; nice to meet you too!
最新文章
- .NET应用架构设计—面向对象分析与设计四色原型模式(彩色建模、领域无关模型)(概念版)
- eclipse代码自动补全[转]
- 探索javascript----滚轮事件的兼容
- springmvc restful配置有一个小小的坑坑
- c语言中,既然不支持函数重载,那么printf算怎么回事?在c语言中,它不就是被重载了吗?
- 【BZOJ】1100: [POI2007]对称轴osi
- 升级到Xcode6.2后 免证书真机调试出错的问题
- 在UI线程之外显示Toast
- Flexbox
- Weka 入门2
- 数据库数据用Excel导出的3种方法
- ASP.Net MVC View
- C#单元测试工具包:MvcContrib
- Xpath语法格式整理
- Yield Usage Understanding
- P、NP、NP完全问题
- Unity 子弹移动以及碰撞条件
- ESP8266 NOOS SDK libat.a Functions
- sync;sync;sync;reboot
- 【转】【Python】Python 中文编码报错