1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
字符串

在说明字符串相关知识的时候,笔者会分为两块分别说明,即C语言格式字符串和C++的string类。 4. 字符串输入输出 知识储备:基本的输入输出知识,包含cin,cout,scanf,printf;基本的数组知识,基本的数据类型,循环,条件语句。 4.1 字符串的定义。 1)C语言格式字符串 定义一个C语言格式字符串很容易,其实质就是一个字符数组。 例:char a[100]; 这里就定义了一个最长为100的字符串。注意这里所说的最长是指在a这个字符串里不能有超过100个的字符,否则会造成数组越界。其实实际上可以使用的空间是99个,这个地方到后面说。 2)C++字符串 定义一个C++字符串更简单。 例:string b;//(需要包含头文件string) 4.2 字符串的输入 C语言格式字符串和C++字符串都可以使用cin输入,cout输出。例如上文中定义的两个字符串我们就可以这样处理: 输入:cina; cinb; 输出:couta; coutb; 我们同样也可以利用scanf和printf来控制输入输出C语言格式字符串,注意其控制符为%s。 例如: 输入:scanf(“%s”,a); 输出:printf(“%s”,a); (注意:这里面控制输入的参数a前并没有取址符,是因为a本来就是一个地址。) (拓展:也可以使用printf来输出C++字符串,其格式为printf(“%s”,b.c_str());仅供了解,不要求掌握)。 由于cin和cout速度相对较慢,对于数目比较庞大的题目我们一般会用scanf和printf处理。 (*难点)4.2含空格的字符串的输入。 我们尝试一下在电脑中输入Hello world!这句话并且让它在屏幕上输出显示出来。 程序代码(错误的): int main() { char str[20]; scanf(“%s”,str); printf(“%s”,str); return 0; } 我们会发现在屏幕上只显示出了Hello。原来,在格式输入控制(包括cin)的时候,当输入遇到了空格,回车,制表符(Tab)时,编译器会判断该字符串输入已经结束。 这时如果想要输入含空格的字符串时,就需要使用gets函数了。 例(上面的那个问题): int main() { char str[20]; gets(str); printf(“%s”,str); return 0; } 这样程序就完美显示了。 例题 4.2.1(POJ3062) Celebrity jeopardy Time Limit:?1000MS Memory Limit:?65536K Total Submissions:?8996 Accepted:?5027 Description Its hard to construct a problem thats so easy that everyone will get it, yet still difficult enough to be worthy of some respect. Usually, we err on one side or the other. How simple can a problem really be?? Here, as in Celebrity Jepoardy, questions and answers are a bit confused, and, because the participants are elebrities, there’s a real need to make the challenges simple. Your program needs to prepare a question to be solved --- an equation to be solved --- given the answer. Specifically, you have to write a program which finds the simplest possible equation to be solved given the answer, considering all possible equations using the standard mathematical symbols in the usual manner. In this context, simplest can be defined unambiguously several different ways leading to the same path of resolution. For now, find the equ

文档评论(0)

82393aa + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档