用C++解决问题第十版 第8章字符串和向量

合集下载

C语言字符串处理掌握字符串的输入输出和处理函数

C语言字符串处理掌握字符串的输入输出和处理函数

C语言字符串处理掌握字符串的输入输出和处理函数C语言字符串处理:掌握字符串的输入输出和处理函数在C语言中,处理字符串是十分重要的。

字符串是一系列字符的集合,在程序中广泛应用于文本处理和数据操作。

掌握字符串的输入输出和处理函数对于编写高效的C语言程序至关重要。

本文将介绍C语言中字符串的输入输出和一些常用的字符串处理函数。

一、字符串的输入输出1. 字符串的输入在C语言中,我们可以使用scanf函数来读取字符串的输入。

需要注意的是,由于scanf遇到空格、制表符或换行符时会停止读取,因此无法直接读取带有空格的字符串。

为了读取完整的字符串,我们可以使用fgets函数。

```c#include <stdio.h>int main() {char str[100];printf("请输入一个字符串:");fgets(str, sizeof(str), stdin);printf("您输入的字符串是:%s\n", str);return 0;}```上述代码中,我们定义了一个大小为100的字符数组str,并使用fgets函数从标准输入读取字符串。

其中sizeof(str)用于指定最大读取的字符数。

2. 字符串的输出在C语言中,我们可以使用printf函数来输出字符串。

需要注意的是,如果字符串中包含格式控制符(如%),需要使用转义字符%来表示。

```c#include <stdio.h>int main() {char str[] = "Hello, World!";printf("字符串输出示例:\n");printf("%s\n", str);return 0;}```上述代码中,我们定义了一个包含字符串"Hello, World!"的字符数组str,并使用printf函数输出该字符串。

C++语言基础教程习题参考解答

C++语言基础教程习题参考解答

清华大学出版社出版普通高等院校计算机专业(本科)实用教程系列之一《C++语言基础教程》全部练习题参考解答第一章 C++语言概述1.2 填空题1.#2. ; { }3. 空格制表回车换行4. 系统用户5. 程序6. 函数头函数体7. main8. 函数原型9. 原型10. 复合语句11. .h .cpp12. 严重错误警告错误13. void14. void15. int 016. n17. 下一行18. 空白符1.3 写出下列程序运行结果,此题又作为上机实验题1. x+y=11,x*y=302. cube(3)=27cube(5)=125cube(8)=5123. averageValue:3averageValue:44. 请输入三个整数:10 5 9 (假定输入的三个整数为10,5,9)最大值: 10最小值: 5第二章数据类型和表达式2.2 填空题1. 4,1,1,4,82. short, int, long4. 46, 123, 985. 107, 10, 92, 42 1026. 157. 符号常量,整数,int8. 3.4E2, 5.27E69. int, int, double, double, float10. x, 1511. 6, 6012. 26, 2513. 4, 114. 256, 2215. x, x16. 0, 117. 2018. 519. 9, 21620. 0, 1921. (1+x)*sin(48*3.14159/180), a*pow(x,b)*exp(x+1)2.3 指出下列各表达式值的类型1. int2. double3. float4. long int5. int6. int7. int8. int9. double 10. double 11. double 12. int13. int 14. double 15. char 16. int17. bool 18. int 19. short 20. bool21. unsigned int 22. double 23. int 24. char25. int 26. double 27. double 28. double29. double 30. int 31. int 32. double33. double 34. double 35. bool 36. bool37. bool 38. bool 39. bool 40. bool2.4 已知a=20, x=4.7, r=’a’, 试求出下列每个表达式的值(各表达式互不影响)。

c语言字符串的用法

c语言字符串的用法

c语言字符串的用法C语言是一种强大且广泛应用的编程语言,字符串是其中一项重要的数据类型。

字符串是由字符组成的字符序列,在C语言中可以使用多种方法来定义、初始化和操作字符串。

1. 字符串的定义和初始化在C语言中,可以使用字符数组或指针来定义和初始化字符串。

1.1 字符数组定义和初始化字符串字符数组是一种固定长度的数组,用于存储字符串。

在定义字符数组时,需要确定它的长度以确保足够存储字符串。

示例:```char str[10]; // 定义一个能够存储10个字符的字符串```在定义并初始化一个字符数组时,可以使用花括号将字符序列围起来,并以空字符 '\0' 结束表示字符串的结束。

示例:```char helloStr[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // 初始化一个包含 "Hello" 的字符串```1.2 字符指针定义和初始化字符串字符指针是指向字符的指针,可以动态分配内存来存储字符串。

通过将字符串赋值给字符指针,即可定义和初始化字符串。

示例:```char *str = "Hello"; // 定义并初始化一个包含 "Hello" 的字符串```2. 字符串的操作和函数在C语言中,提供了多个字符串操作的函数,以便对字符串进行处理和操作。

2.1 字符串的输出可以使用printf函数来输出字符串。

示例:```char str[] = "Hello";printf("%s", str); // 输出字符串 "Hello"```2.2 字符串的拼接可以使用strcat函数将两个字符串拼接在一起。

示例:```char str1[] = "Hello";strcat(str1, str2); // 拼接字符串,结果为 "HelloWorld"```2.3 字符串的比较可以使用strcmp函数对两个字符串进行比较。

C++程序设计课件 第10课 C++字符串

C++程序设计课件 第10课 C++字符串

第10课 C++字符串1、基本操作--------------------------------------------------------------------- #include <iostream>#include <string>using namespace std;int main(){string s1="abcde",s2="ABCDE",s;s=s1+s2;cout<<s<<endl;cout<<s.size()<<endl;return 0;}--------------------------------------------------------------------- 2、字符串实例-大写转小写--------------------------------------------------------------------- #include <iostream>#include <string>using namespace std;int main(){string s="abcdeABCDE";for(int i=0;i<s.size();++i){if(s[i]>='A' && s[i]<='Z')s[i]=s[i]+32;}cout<<s<<endl;return 0;}--------------------------------------------------------------------- 3、倒序--------------------------------------------------------------------- #include <iostream>#include <string>using namespace std;int main(){string s("当周围变得寂静无声的时候,你就是高手了!");string s1;s1=s;for(int i=0;i<s.size();++i)s1[i]=s[s.size()-i-1];cout<<s1<<endl;return 0;}--------------------------------------------------------------------- 4、变码--------------------------------------------------------------------- #include <iostream>#include <string>using namespace std;int main(){string s("µ±ÖÜΧ±äµÃ¼Å¾²ÎÞÉùµÄʱºò£¬Äã¾ÍÊǸßÊÖÁË£¡");string s1;s1=s;for(int i=0;i<s.size();++i)s1[i]=s[i]+5;cout<<s1<<endl;return 0;}--------------------------------------------------------------------- 5、查找子串位置--------------------------------------------------------------------- #include <iostream>#include <string>using namespace std;int main(){string s="abcde";string s1="cd";int n;n=s.find(s1,0);cout<<n<<endl;return 0;}--------------------------------------------------------------------- 6、查找并替换子串---------------------------------------------------------------------#include <iostream>#include <string>using namespace std;int main(){string s="abÁõ¶«Ã÷cde";string s1="Áõ¶«Ã÷";int n;cout<<s<<endl;n=s.find(s1,0);s.replace(n,s1.size(),"ÇúÒÕ");cout<<s<<endl;return 0;}--------------------------------------------------------------------- 7、查找并删除子串--------------------------------------------------------------------- #include <iostream>#include <string>using namespace std;int main(){string s="ab刘东明cde";string s1="刘东明";int n;cout<<s<<endl;n=s.find(s1,0);s.erase(n,s1.size());cout<<s<<endl;return 0;}--------------------------------------------------------------------- 8、查找并取出子串--------------------------------------------------------------------- #include <iostream>#include <string>using namespace std;int main(){string s="ab刘东明cde";string s1="刘东明";string s2;int n;cout<<s<<endl;n=s.find(s1,0);s2=s.substr(n,s1.size());cout<<s2<<endl;return 0;}--------------------------------------------------------------------- 9、实例-算式解析--------------------------------------------------------------------- #include <iostream>#include <string>#include <sstream>using namespace std;int str2num(string s){int n;stringstream ss;ss<<s;ss>>n;return n;}int main(){string s="1+2",s1,s2;int n1,n2;n1=s.find("+",0);n2=n1+1;s1=s.substr(0,n1);s2=s.substr(n2,s.size()-n2);cout<<s1<<endl;cout<<s2<<endl;cout<<str2num(s1)+str2num(s2)<<endl;return 0;}--------------------------------------------------------------------- 10、实例-英汉词典解析---------------------------------------------------------------------#include <iostream>#include <string>#include <sstream>using namespace std;int main(){string s="ability n.能力",s1,s2;int n1,n2;n1=s.find(" ",0);n2=n1;while(true){++n2;if(s.substr(n2,1)!=" ")break;}s1=s.substr(0,n1);s2=s.substr(n2,s.size()-n2);cout<<s1<<endl;cout<<s2<<endl;return 0;}--------------------------------------------------------------------- 11、演示:单串数据库-学生成绩管理系统(实验准备)--------------------------------------------------------------------- 程序:略。

程序设计与算法(一)C语言程序设计新标准C++习题解答chapter1-10

程序设计与算法(一)C语言程序设计新标准C++习题解答chapter1-10

《新标准C++程序设计》习题解答第1章-第10章郭炜第一章1.将下列十进制数表示成16位二进制形式和4位十六进制形式:255,-254,-1,10,20,-12。

解答:题目的意思是,如果在计算机内部用16位二进制形式和4位16进制形式表示上面的数,会是什么样子。

要求最高位是符号位,负数的符号位是1。

因此答案为:255: 0000 0000 1111 1111,00FF-254: 1111 1111 0000 0010, FF02-1: 1111 1111 1111 1111, FFFF10:0000 0000 0000 1010, 000A20:0000 0000 0001 0100,0014-12:1111 1111 1111 0100, FFF42.将下列16位的有符号二进制数转换成十进制形式:1000 1111 0000 1111, 0000 1011 0000 1111, 1111 1111 0000 11111111 1111 1111 1110, 1000 0000 0000 0000, 0000 0000 1100 1110解答:-28913,2831,-241,-2,-32768,2063.将下列有符号4位16进制数转换为十进制数:FC34, 7000, 00a5, 1004, 7F45, 7700, C0C0, 0FFF,FFFF解答:-972,28672,165,4100,32581,30464,-16192,4095,-1,第二章1. 以下哪些是合法的C++标识符,哪些不是?2Peter__day_num_ofsch-name;解答:第一个和第四个不是,因为标识符不能以数字开头,中间不能有除了“_”和“-”以外的标点符号。

其他的是合法的。

2. 编写一个程序,输入3个整数,输出他们的平均数。

解答:#include <iostream>using namespace std;int main(){int a,b,c;cin >> a >> b >>c;cout << (a+b+b)/3.0;return 0;}3. 说出下面各个类型的变量所占的字节数和表示范围:short , int, unsigned int, long long, unsigned char, char解答:参见本章正文4. 已知字母'a'的ASCII码是97,请写出下面程序的输出结果:#include <iostream>using namespace std;int main(){int n1 = 'a';unsigned short n2 = 0xffff;int n3 = n2;short n4 = n2;cout << n1 << "," << n2 << "," << n3 << "," << n4 << endl;double f = 6/5;n3 = 5/(double) 2;char c = 102;int n5 = 0xffffffff + 2;cout << c << "," << f << "," << n3 << "," << n5 << endl;return 0;}解答:97,65535,65535,-1f,1,2,1解释:n4是有符号的,会表示负数,n4=n2执行后,n4的内容是n2的拷贝,即n4最高位为1,表示负数,因此输出n4,得-15. 计算下列表达式的值(答案可写十六进制)(1) 5 * 4 / 3 + (7 % 2)(2) 0xfff4 >> 2(3) 0xea8 << 3(4) 12 ^ 23(5) ~24(6) 0x7fff0000 >> 3解答:(1)7(2)3ffd(3)7540(4)1b(5)ffffffe7(6)fffe0006. 已知有 int a = -10, b = 20, c = 30; 请写出以下每个表达式计算结束后a的值。

编译原理课后题答案【清华大学出版社】ch8

编译原理课后题答案【清华大学出版社】ch8

如果题目是 S::=L.L | L L::=LB | B B::=0 | 1 则写成: S`::=S {print(S.val);} S::=L1.L2 { S.val:=L1.val+L2.val/2L2.length ;} S::= L { S.val:=L.val; } L::=L1B { L.val:=L1.val*2+B.val; L.length:=L1.length+1; } L::=B { L.val:=B.val; L.length:=1;} B::=0 { B.val:=0; } B::=1 { B.val:=1;}
如采用 LR 分析方法,给出表达式(5*4+8)*2 的语法树并在各结点注明语义值 VAL。
答案:
计算机咨询网()陪着您
5
缄默TH浩的小屋
《编译原理》课后习题答案第八章
采用语法制导翻译思想,表达式 E 的“值”的描述如下:
产生式
语义动作
(0) S′→E
{print E.VAL}
四元式:
100 (+, a, b, t1) 101 (+, c, d, t2) 102 (*, t1, t2, t3) 103 (-, t3, /, t4) 104 (+, a, b, t5) 105 (+, t5, c, t6) 106 (-, t4, t6, t7)
树形:
计算机咨询网()陪着您
计算机咨询网()陪着您
6
缄默TH浩的小屋
《编译原理》课后习题答案第八章
第5题
令 S.val 为下面的文法由 S 生成的二进制数的值(如,对于输入 101.101,S.val=5.625); SÆL.L | L LÆLB | B BÆ0 | 1

C语言字符串处理技巧

C语言字符串处理技巧

C语言字符串处理技巧C语言是一种广泛应用于系统开发和嵌入式领域的编程语言,字符串处理是其中一个重要的方面。

在本文中,我们将介绍一些C语言中常用的字符串处理技巧,帮助读者更加熟练地处理和操作字符串。

1. 字符串的定义和初始化在C语言中,字符串被定义为字符数组,以一个空字符 '\0' 结尾,用于标识字符串的结束。

下面是一个字符串的定义和初始化的示例:```cchar str[10] = "Hello";```在该示例中,字符数组 `str` 的大小为10,初始化为 "Hello"。

需要注意的是,字符数组的大小应至少比字符串的长度多1,以留出空字符的位置。

2. 字符串的输入和输出使用C语言的标准输入输出函数,我们可以方便地输入和输出字符串。

下面是一个字符串输入和输出的示例:```c#include <stdio.h>int main() {char str[100];printf("请输入一个字符串:");scanf("%s", str);printf("您输入的字符串是:%s", str);return 0;}```在该示例中,使用 `scanf` 函数读取一个字符串,并使用 `printf` 函数输出该字符串。

3. 字符串的拼接C语言提供了 `strcat` 函数可以用来将两个字符串拼接在一起。

下面是一个字符串拼接的示例:```c#include <stdio.h>#include <string.h>int main() {char str1[20] = "Hello";char str2[10] = "World";strcat(str1, str2);printf("拼接后的字符串是:%s", str1);return 0;}```在该示例中,使用 `strcat` 函数将字符串 `str2` 拼接到字符串 `str1` 的末尾,得到拼接后的字符串 "HelloWorld"。

用C++解决问题第十版Chapter 8

用C++解决问题第十版Chapter 8

TRUE/FALSE1.The following code declares a vector of characters.vector characters<char>ANSWER: FALSE2.The following code declares a vector of integers named numbers that reservesspace for 100 integers.vector<int> numbers(100);ANSWER: TRUE3.Vectors can have any type as the base typeANSWER: TRUE4.Vectors and arrays are the same data type.ANSWER: FALSEing the == operator on a string variable results in the same value as usingstrcmp on two c-strings.ANSWER: FALSEing the [i] on a string variable does not check for illegal values of i.ANSWER: TRUE7. A string variable and a c-string are the same data type.ANSWER: FALSE8.The function used to 'put two c-strings together into one" is calledANSWER: strcat9.The following declares a c-string and initializes it to "speaker"char str[]="speaker";ANSWER: TRUE10.The following declares a c-string variable that will hold 10 letters.char str[10];ANSWER: FALSE11.Vector assignment is well behaved.ANSWER: TRUE12.If v is a vector and i is an int variable, then in the following the value ofi can be any nonnegative int value:v[i] = i;ANSWER: FALSE13.If we use an out of range index with a vector, there will be an error message fromthe compiler.ANSWER: FALSE.ing the resize member function alone, you can increase the capacity of an STLvector.ANSWER: TRUE15.If vector v has fewer than 24 elements and you call v.resize(24) the newlyallocated elements are not initialized.ANSWER: FALSE.16.You can explicitly use the vector member function resize to increase the capacityof a vector.ANSWER: TRUE17.A vector v will automatically increase the allocated size when more than v.size( )elements are inserted with v.push_back( newElement).ANSWER: TRUE.18.Vector indexing warns about out-of-bounds index values.ANSWER: FALSE.Short Answer1.The character '\0' is called the __________ character.ANSWER: NULL2.All c-strings must be terminated by ________ANSWER: the null character3.To compare two c-strings you use the __________ function.ANSWER: strcmp or strncmp4.To use the functions for manipulating and comparing c-strings, you must include___________ANSWER: <cstring>5.What is the c-string function to determine the number of characters in a c-string?ANSWER: strlen6.What is the difference between strcat and strncat?ANSWER: strncat will concatenate at most n letters (where n has an appropriate value).7.How do you call the function to read a whole line of input(up to 80 characters)from the keyboard into a c-string named str?ANSWER: cin.getline(str,80);8.What is the name of the function to convert from a c-string that contains onlydigits to an integer?ANSWER: atoi9.The c-string to number conversion functions are in the _________ library.ANSWER: cstdlib10.To use the string class, you must include which library?ANSWER: <string>11.The ________ class lets you treat string values and variables like other pre-defined data types (such as int).ANSWER: string12.How do you concatenate two string values (str1, str2)?ANSWER: str1 = str1 + str2; or str1 += str2;13.What is the code to print out the third character in a string variable named str?ANSWER: cout << str[2];14.Which string function returns the first occurrence of str1 in a string named str?ANSWER: find15.____________ can be thought of as an array that can grow and shrink as needed.ANSWER: Vectors16.The declaration of an STL vector doubleVec that can hold values of type double,one writes ______________.ANSWER: vector<double> doubleVec;17.To change the space already allocated for a vector, one uses the ______________member function.ANSWER: reserve18.To change the size of a vector, one uses the ______________ member function.ANSWER: resize19.To convert a string object that stores an integer to a variable of type int one canuse the C++11 function ____________.ANSWER: stoi20.To convert an integer to a variable of type string one can use the C++11 function_____________.ANSWER: to_stringMultiple Choice1. A character array terminated with the null character is most correctly calleda. a c-stringb. a character arrayc. a stringd.none of the aboveANSWER: A2.Which of the following declarations correctly creates a c-string that can hold thevalue "phonebook"a.char s1;b.char s1[9];c.char s1=10;d.char s1[10];ANSWER: D3.To declare a c-string and initialize it to the value of "phonebook",a.char s1=phonebook;b.char s1[10]="phonebook";c.c-string phonebook;d.char s1[10]=phonebook;ANSWER: B4.Which of the following will print out the value in str?char str[30];cin >> str;a.cout << str;b.for(int i=0;i<30;i++)cout << str[i];c.int i=0;while(i<30 && str[i] != '\0')cout << str[i];d.All of the abovee. A and Bf. A and CANSWER: F5.When the extraction operator is used to read data into a string,a.it skips all white spacesb.it skips only new linesc.it reads everything on the lined.it reads as many characters that will fit into the c-stringANSWER: A6.If you want to read into a c-string, you must ensure that the user does not entermore characters thana.The size of the c-stringb.The size of the c-string + 1c.The size of the c-string -1d.It doesn't matter.ANSWER: C7.What is wrong with the following attempted c-string declaration and initialization?char str1[5]={'a', 'b', 'c'};a.There are only 3 values in the bracesb.The single quotes should be double quotesc.The values do not constitute a c-stringd.nothingANSWER: C8.How can you assign the value "toaster" to a c-string name str of size 10?a.str="toaster;b.str=toaster;c.strcpy(str,"toaster");d.str.strcpy("toaster");ANSWER: C9.What is the difference between strcmp and strncmp?a.No differenceb.they both compare, one expects an integer for the number of characters tocompare.c.one copies, the other comparesd.They are in different librariesANSWER: B10.strcmp(first, second) returnsa.<0 if first < second, 0 if first == second, positive otherwiseb.true if first=second, false otherwisec.nothing, it's a void functiond.>0 if first < second, 0 if first > second, <0 otherwiseANSWER: A11.What is wrong with the following code fragment?char str1[10]="Mark", str2[15]="What's my name";strcpy(str1,str2);a.Nothingb.str2 has white space in itc.str1 does not have enough roomd.str2 does not have enough roomANSWER: C12.Which assignment statements will copy the value " toaster" into a string variable(str1)?a.strcpy(str1,"toaster");b.str1 = "toaster";c.str1 = toaster;d.str1 += toaster;ANSWER: B13.What is the value of str after the following code?string str;a. a garbage stringb.the empty stringc.the null characterd.unknownANSWER: B14.Which is the proper way to determine how many characters are in the stringvariable named str?a.str.getLength()b.str.length()c.length(str)d.getLength(str)ANSWER: B15.If the name of a file to open is in the string variable name fileName, which of thefollowing will correctly open the file for output?a.out_file.open(fileName);b.out_file.open("fileName");c.fileName.open(outfile);d.out_file.open(fileName.c_str());ANSWER: D16.Which of the following would correctly read an entire line from an input filestream named fin into a string variable named line.a.getline(fin, line);b.fin.getline(line);c.fin.getline(line,'\n\');d.fin.getline(line,80);ANSWER: A17.Which of the following returns the fourth character in the string variable namedstr and checks if there is a fourth character in the string?a.str(3);b.str.at(3);c.str[3];d.All of the aboveANSWER: B18.Given the following declarations, which of the following is legal syntax?string str="Your name";char c_string[20]="My name";a.str = c_string;b.c_string = str;c.strcpy(c_string, str.c_str());d.strcpy(c_string, str);e. A and CANSWER: E19.The notation vector<Base_Type> means that the vector isa.an arrayb. a template classc.primitive data typed.all of the aboveANSWER: B20.The base type for a vector can bea.intb.float or doublec.chard.any data typeANSWER: D21.What is the proper way to declare a vector of strings named names?a.vector strings names;b.vector<names> string;c.vector<string> names;d.all of the aboveANSWER: C22.To add an element to a vector of integers named numbers at the next availableposition in the vector, you would use:a.numbers[numbers.size()+1] = newValue;b.numbers = newValue;c.numbers.pushBack(newValue);d.numbers.push_back(newValue);ANSWER: D23.What is the value of numbers.size() after the following code?vector<float> numbers;a.0b.10c.100d.unknownANSWER: A24.What is the value of numbers.size() after the following code?vector<float> numbers(100);a.0b.10c.100d.unknownANSWER: C25.What is the value of numbers.size() after the following code?vector<float> numbers;numbers.reserve(100)a.0b.10c.100d.unknownANSWER: A26.What is the value of numbers.capacity() after the following code?vector<float> numbers;numbers.reserve(100)a.0b.10c.100d.unknownANSWER: C27.When a vector is assigned to another vectora.only the location of the vector is copiedb.all the values in the vector are copiedc.if there is not enough room in the left-hand vector, then not all the valuesfrom the right side are copiedd.none of the aboveANSWER: B28.If a vector named numbers has 20 elements in it, what is the result of executingthe following statement?numbers.resize(10);a.no changeb.the first 10 elements are removedc.the last 10 elements are removedd.this causes a run-time errorANSWER: C29.If the capacity of a vector named names is 20 and the size of names is 19, whichof the following statements are legal?s.push_back("myName");s[18]="myNmae";c.all of the aboved.none of the aboveANSWER: D30.Given the following code, what is the correct statement to insert the string str2into str1, directly after the 'd'?string str1="abcdefg";string str2="ABCDE";a.str1.insert(4,str2);b.str2.insert(4,str1);c.insert(str1,4)=str2;d.insert(str2,4)=str1;ANSWER: A31.In a vector, which of the following statements is true?a)Indexing vector access is range checked.b)The range of legal index values for a vector is 0 to the value of v.size()-1c)To add a value use the member function v.push_front( )d)To increase or decrease a vector’s size v.new_size(newSize);ANSWER: B32.Which of the following are correct statements about vector member functionsstudied in this chapter?a)push_front (baseTypeObject) puts object on the front of a vectorb)indexing uses index values 0 through size( )c)size( ) tells how many base type objects have been inserted into the vectord)When a vector runs out of space all implementations are required to doublethe amount of allocated space .ANSWER: C。

华北电力大学c++字符串和函数答案

华北电力大学c++字符串和函数答案

华北电力大学c++字符串和函数答案第1题:编写程序,从键盘输入一任意字符串(不包含空格),然后输入所要查找字符。

如果存在则输出它在字符串中第一次出现的位置,否则输出NO。

样例输入:Hello a 样例输出:NO 样例输入:Hello l 样例输出:2#include //#include int main() {int m=0,p=0; char s[50],t; cin>>s>>t; //cin>>t;while(s[p]!='\\0') if(s[p]==t) {m=1;break;} else p++;if(m==0) cout #include int main() {char word1[50],word2[25]; int p=0,e,j; cin>>word1;strcpy(word2,word1); j=strlen(word2); e=j-1; while(p #include int main() {int p=0,flag=0; char c1[20],c2[20]; cin>>c1>>c2;while((flag==0)&&(c1[p]!='\\0')&&(c2[p]!='\\0')) { if(c1[p]==c2[p]) p+=1; else flag=1; }if(flag==1) cout第4题:编写程序,输入字符串(不包含空格),统计英文字母、数字字符及其他字符的个数。

样例输入:abc129++*ABC 样例输出:6 3 3 #include int main() {intnum=0,word=0,symbol=0,i; char c[100]; cin>>c;for(i=0;c[i]!='\\0';i++) {if(c[i]='0') num=num+1;else if (c[i]>='a'&&c[i]='A'&&c[i] #include int main() {char letter[100]; int i;cin>>letter;for(i=0;letter[i]!='\\0';i++) {letter[i]=letter[i]+4;if (letter[i]>'z'&&letter[i]'Z'&&letter[i]intgys(intm,int n) { int r; if(m>a>>b; c=gys(a,b);d=a*b/c;cout int digit(intnum,int k) {intb,i=0; do{b=num ; num=num/10; i++;}while(num>0&&i0&&i==k) return b; else return 0; }int main() {inta,b,n; cin>>n>>b; a=digit(n,b); cout第3题:哥德巴赫猜想指出:任何一个不小于6的偶数都可以表示为两个素数之和。

用C++解决问题第十版Chapter2

用C++解决问题第十版Chapter2

用C++解决问题第十版Chapter2TRUE/FALSE1.In the following code fragment, x has the value of 3.int x = 3;ANSWER: TRUE2.The body of a do-while loop always executes at least once.ANSWER: TRUE3.The body of a while loop may never execute.ANSWER: TRUE4.The opposite of (x >3 && x < 10) is (x < 3 && x > 10)ANSWER: FALSE5.The integer 0 is considered true.ANSWER: FALSE6.Loops are used when we need our program to make a choice between two or morethings.ANSWER: FALSE7.It is legal to declare more than one variable in a single statement.ANSWER: TRUE8.Variable names may begin with a number.ANSWER: FALSE9.The opposite of less than is greater thanANSWER: FALSE10.Every line in a program should have a comment.ANSWER: FALSEShort Answer1.<< is called the stream ____________________ operator.ANSWER: insertion2.The braces for a loop define the ____________ of the loop.ANSWER: body3. A loop that always executes the loop body at least once is known as a_____________ loop.ANSWER: do-while4.int myValue; is called a _______________________.ANSWER: variable declaration5.What is the opposite of ( x < 20 && x > 12)? _______________________ANSWER: (x >=20 || x <= 12)6.What is the correct conditional statement to determine if x is between 19 and 99?__________________ANSWER: (x >19 && x < 99)7.Each time a loop body executes is known as an _______________________.ANSWER: iteration8.if-else statements that are inside other if-else statements are said to be_______________.ANSWER: nested9.>> is known as the stream ____________ operator.ANSWER: extraction10.Is << used for input or output? ____________ANSWER: output11.The stream that is used for input from the keyboard is called ___________.ANSWER: cin12.The stream that is used for output to the screen is called___________.ANSWER: cout13.Write the loop condition to continue a while loop as long as x is negative.____________________ANSWER: while(x < 0)14.When must we use braces to define the body of a contitional expression?______________ANSWER: When there are multiple statements in the body.15.In a compound logical and (&&) expression, the evaluation of the expressionstops once one of the terms of the expression is false. This is known as______________ evaluation.ANSWER: short-circuit evaluation16.The _______ keyword in C++11 determines the type of a variable based on thedata type that the variable is set to.ANSWER: autoMultiple Choice1.Which of the following is a valid identifier?a.3comb.three_comc.3_comd.3-come.dollar$ANSWER: C2.Which of the following is not a valid identifier?a.returnb.myIntc.myIntegerd.total3ANSWER: A3.What is the value of x after the following statements? int x, y, z;y = 10;z = 3;x = y * z + 3;a.Garbageb.60c.30d.33ANSWER: D4.What is the value of x after the following statements? int x;x = 0;x = x + 30;a.0b.30c.33d.garbageANSWER: B5.What is the value of x after the following statements? int x;x = x + 30;a.0b.30c.33d.garbageANSWER: D6.What is the output of the following code?float value;value = 33.5;cout << value << endl;a.33.5b.33c.valued.garbageANSWER: A7.What is the output of the following code?float value;value = 33.5;cout << "value" << endl;a.33.5b.33c.valued.garbageANSWER: C8.What is the output of the following code?cout << "This is a \\" << endl;a.This is ab.This is a \c.nothing, it is a syntax errord.This is a \ endlANSWER: B9.Which of the following lines correctly reads a value from the keyboard and storesit in the variable named myFloat?a.cin > > myFloat;b.cin << myFloat;c.cin >> "myFloat";d.cin >> myFloat >> endl;ANSWER: A10.Another way to write the value 3452211903 isa. 3.452211903e09b. 3.452211903e-09c. 3.452211903x09d.3452211903e09ANSWER: A11.Which of the following statements is NOT legal?a.char ch='b';b.char ch='0';c.char ch=65;d.char ch="cc";ANSWER: D12.What is the value of x after the following statements? float x;x = 15/4;a. 3.75b. 4.0c. 3.0d.60ANSWER: C13.What is the value of x after the following statements? int x;x = 15/4;a.15b. 3c. 4ANSWER: B14.What is the value of x after the following statements? int x;x = 15 %4;a.15b. 4c. 3d. 3.75ANSWER: C15.What is the value of x after the following statement? float x;x = 3.0 / 4.0 + 3 + 2 / 5a. 5.75b. 5.75c. 1.75d. 3.75ANSWER: D16.What is the value of x after the following statement? float x;x = 3.0 / 4.0 + (3 + 2 )/ 5a. 5.75b. 5.75c. 1.75d. 3.75ANSWER: C17.What is the value of x after the following statements? double x;x = 0;x += 3.0 * 4.0;a.22.0b.12.0c.10.0d.14.0ANSWER: C18.Given the following code fragment and the input value of 4.0, what output isgenerated?float tax;float total;cout << "enter the cost of the item\n";cin >> total;if ( total >= 3.0){tax = 0.10;cout << total + (total * tax) << endl;}else{cout << total << endl;}a. 3b. 3.3c. 4.0d. 4.4ANSWER: D19.Given the following code fragment and the input value of 2.0, what output isgenerated?float total;cout << "enter the cost of the item\n";cin >> total;if ( total >= 3.0){tax = 0.10;cout << total + (total * tax) << endl;}else{cout << total << endl;}a. 2.2b. 2.0c. 3.1d. 4.4ANSWER: B20.If x has the value of 3, y has the value of -2, and w is 10, is the followingcondition true or false?if( x < 2 && w < y)a.trueb.falseANSWER: B21.What is the correct way to write the condition y < x < z?a.(y < x < z)b.( (y < x) && z)c.((y > x) || (y < z))d.((y < x) && (x < z))ANSWER: D22.Given the following code fragment, and an input value of 3, what is the outputthat is generated?int x;cout <<"Enter a value\n";cin >> x;if(x=0){cout << "x is zero\n";}else{cout << "x is not zero\n";}a.x is zerob.x is not zeroc.unable to determined.x is 3ANSWER: A (note it is an assignment!)23.Given the following code fragment, and an input value of 5, what is the output?int x;if( x< 3){cout << "small\n";}else{if( x < 4){cout << "medium\n";}else{if( x < 6){cout << "large\n";}else{cout << "giant\n";}}}a.smallb.medium/doc/cc10453636.html,rged.giantANSWER: C24.Given the following code fragment, what is the output? int x=5;if( x > 5)cout << "x is bigger than 5. ";cout <<"That is all. ";cout << "Goodbye\n";a.x is bigger than 5. That is allb.x is bigger than 5c.That is all. Goodbyed.GoodbyeANSWER: C25.Executing one or more statements one or more times is known as:a.selectionb.iterationc.sequenced.algorithmANSWER: B26.Given the following code fragment, what is the final value of y?int x, y;x = -1;y = 0;while(x <= 3){y += 2;x += 1;}a. 2b.10c. 6d.8ANSWER: B27.Given the following code fragment, what is the final value of y?int x, y;x = -1;y = 0;while(x < 3){y += 2;x += 1;}a. 2b.10c. 6d.8ANSWER: D28.What is the output of the following code fragment?int x=0;while( x < 5)cout << x << endl;x ++;cout << x << endl;a.0b. 5c. 4d.unable to determineANSWER: D (infinite loop)29.What is the final value of x after the following fragment of code executes?int x=0;do{x++;}while(x > 0);a.8b.9c.10d.11e.infinite loop.ANSWER: E30.Given the following code fragment, which of the following expressions is alwaystrue?int x;cin >> x;a.if( x < 3)b.if( x==1)c.if( (x / 3) >1 )d.if( x = 1)ANSWER: D31.What is the advantage of the C++11 integer data types over the old data types?a.Number of bits allocated changes dynamically as neededb.No advantage, just new namesc.Specifies exact size in bitsd.Higher precisionANSWER: C。

C++Primer 第8章-标准IO库-课后习题答案

C++Primer 第8章-标准IO库-课后习题答案

第八章标准IO库8.1 假设os是一个ofstream对象,下面程序做了什么?os << “Goodbye!” << endl;如果os 是ostringstream对象呢?或者,os 是ifstream对象呢?答:第一个,向文件中写入”Goodbye”, 第二个向string对象中写入”Goodbye”,第三个,如果os是一个ifstream对象,则错误,因为ifstream类中没有定义操作符<< 。

8.2 下面的声明是错误的,指出其错误并改正之: ostream print(ostream os);答:标准库类型不允许做复制或赋值操作。

形参或返回类型不能为流类型,所以上句代码错误,因为它把流类型的对象当做了形参。

应改为传递指向该对象的指针或引用:ostream &print( ostream &os );8.3 编写一个函数,其唯一的形参和返回值都是istream&类型。

该函数应一直读取流直到到达文件的结束符为止,还应将读到的内容输出到标准输出中。

最后,重设流使其有效,并返回该流。

答:#include"stdafx.h"#include<iostream>using namespace std;istream & f( istream & in ){int ival;while ( in >> ival, !in.eof()) // 遇到文件结束符之前一直读入数据{if(in.bad()) // input stream is corrupted; bail out, 流是否已被破坏throw runtime_error("IO stream corrupted");if ( in.fail() ) // bad input{cerr << " bad date, try again:";in.clear( ); // reset the streamin.setstate(istream::eofbit); // 结束死循环continue;}// process inputcout << ival << endl;}in.clear(); // 将in中的所有状态值都设为有效状态return in;}int main(){cout << " Input some words ( ctrl + z to end ):\n";f( cin );system("pause");return 0;}8.4 通过cin为实参实现调用来测试上题编写的函数。

郑秋生版c++答案习题八

郑秋生版c++答案习题八

第八章指针与引用习题答案一、选择题CBCBCC二、简答题(1)&运算符:取地址运算符,用来得到一个普通变量的地址。

*运算符:间接引用运算符,用来获取指针变量所指向变量的值。

(2)指针:一个变量在内存中所占存储单元的首地址称为该变量的指针,也就是指向该变量的指针。

指针中存储的地址是其所指向的变量的地址,指针中存储的地址里的值就是其所指向变量的值。

(3)引用与指针的区别是,通过某个指针变量指向一个对象后,对它所指向的变量通过*运算符进行间接操作,程序中使用指针,程序的可读性差;而引用本身就是目标变量的别名,对引用的操作就是对目标变量的操作。

可以建立数组的指针,但不能建立数组的引用,因为数组是一个由若干个元素所组成的,所以就无法建立一个数组的别名。

(4)const int *p1 表示p1所指向的int变量为常量,int *const p1 表示p1为常量三、改错题(1)int a;b; 改成int a, b;pointer_1=a; 改成pointer_1=&a;cout<<*a<<" "<<*b<<endl; 改成cout<<a<<" "<<b<<endl;cout<<pointer_2*a<<endl; 改成cout<<(*pointer_2)*a<<endl;(2)有int *p,a=9;p=&a;cout<<”the value of p is ”<<*p;四、阅读程序写结果(1)ABCDEFG(2)x=1.5 y=2.5z=4(3)20 50 50 41(4)m-n=15五、编程题(1)实现字符串逆序输出。

#include <iostream.h>#include <string.h>const char *fun( const char *p1 ){while (*p1++);p1--;return p1;}int main(void){char s1[100];const char *q,*p1;cout<<"输入一个字符串:";cin.getline( s1,100);cout<<"逆向输出串:";q=s1;p1=fun(s1);do{cout<<*p1;p1--;}while(q<=p1);return 0;}(2)输入任意一个字符串,将其中的大写字母转换成小写字母。

c++算法 八数码问题

c++算法 八数码问题

c++算法八数码问题八数码问题是一种经典的智力游戏,其规则是在有限的格子中,按照一定的顺序将数字旋转移动到目标位置。

为了解决这个问题,我们可以使用算法的思想来设计一种有效的解决方案。

一、问题描述八数码问题是一个有N×N的棋盘,其中每个格子代表一个数字。

玩家需要按照一定的顺序旋转数字,将它们移动到目标位置。

目标位置是预先设定好的,玩家需要按照规则移动数字,使得棋盘上的数字按照正确的顺序排列。

二、算法思想为了解决八数码问题,我们可以使用贪心算法的思想。

首先,我们需要找到一个初始状态,这个状态应该是最简单、最容易解决的问题。

然后,我们通过循环迭代的方式,不断尝试不同的旋转方式,直到找到一个能够满足目标位置的解决方案。

三、C语言实现下面是一个简单的C语言实现,用于解决八数码问题。

这个程序使用了递归和回溯的方法,通过穷举所有可能的旋转方式来找到解决方案。

```c#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#define N 3// 定义棋盘状态结构体typedef struct {int nums[N][N];int num_count[N][N]; // 记录每个数字出现的次数} Board;// 判断两个数字是否相邻bool is_adjacent(int num1, int num2) {int dx[] = {-1, 0, 1};int dy[] = {0, -1, 1};for (int i = 0; i < 3; i++) {if (abs(nums[num1][i] - nums[num2][i]) <= 1) {return true;}}return false;}// 寻找最优解函数bool find_optimal_solution(Board& board, int target_row, int target_col) {// 初始化最优解为空状态bool optimal_solution = false;int optimal_score = INT_MAX; // 最优解的得分初始化为最大整数int best_score = INT_MAX; // 最优解的当前得分初始化为最大整数加一// 对当前棋盘进行遍历for (int row = 0; row < N; row++) {for (int col = 0; col < N; col++) {// 如果当前状态为空状态,则直接跳过if (board.nums[row][col] == 0) {continue;}// 记录当前状态的信息,包括得分和旋转次数等int score = calculate_score(board, row, col); // 计算得分函数在实现中定义了旋转方式的选择和得分计算规则等具体细节,这里省略了具体实现细节。

0x02_字符串、向量和数组

0x02_字符串、向量和数组

0x02_字符串、向量和数组字符串、向量和数组命名空间的using声明std::cin表⽰从标准输⼊中读取内容,此处使⽤作⽤域操作符(::)的含义是:编译器应从操作符左侧名字所⽰的作⽤域中寻找右侧那个名字。

因此,std::cin的意思就是要使⽤命名空间std中的名字cin。

最安全的⽅式是使⽤using声明来更简单的使⽤命名空间中的成员:using namespace::name;#include <iostream>using std::cin;int main() {int i;cin >> i;cout << i;std::cout << i;return 0;}按照规定,每个using声明引⼊命名空间中的⼀个成员。

位于头⽂件的代码⼀般来说不应该使⽤using声明。

这是因为头⽂件的内容会拷贝到所有引⽤它的⽂件中去,如果头⽂件⾥有某个using声明,那么每个使⽤了该头⽂件的⽂件就都会有这个声明。

对于某些程序来说,由于不经意间包含了⼀些名字,反⽽可能产⽣始料未及的名字冲突。

标准库类型stringstring表⽰可变长的字符序列。

定义和初始化string对象如何初始化类的对象是由类本⾝决定的。

⼀个类可以定义很多种初始化对象的⽅式,只不过这些⽅式之间必须有所区别:或者是初始值的数量不同,或者是初始值的类型不同。

直接初始化和拷贝初始化:如果使⽤等号初始化⼀个变量,实际上执⾏的是拷贝初始化,编译器把等号右侧的初始值拷贝到新创建的对象种去。

与之相反,如果不使⽤等号,则执⾏的是直接初始化。

当初始值只有⼀个时,使⽤直接初始化或拷贝初始化都⾏。

如果像s4那样初始化要⽤到的值有多个,⼀般来说只能使⽤直接初始化的⽅式:string s5 = "hiya"; // 拷贝初始化string s6("hiya"); // 直接初始化string s7(10, 'c'); // 直接初始化string对象上的操作在执⾏读取操作时,string对象会⾃动忽略开头的空⽩(即空格符、换⾏符、制表符等)并从第⼀个真正的字符开始读起,直到遇见下⼀处空⽩为⽌。

C++课程实习及答案全解之欧阳法创编

C++课程实习及答案全解之欧阳法创编

实验题目(共4题, 第1题)标题: 1、字符串输入输出时限: 1000 ms内存限制: 10000 K总时限: 3000 ms描述:编写一个简单的控制台应用程序,先输入姓名,如“John”,再输出问候语,如“Hello, John!”。

输入: John输出: Hello, John!输入样例: John输出样例: Hello,John!提示:1、使用string类定义字符串对象,需包含头文件<string>;2、使用cin和提取符>>从键盘输入数据,使用cout和插入符<<输出结果到屏幕,需包含头文件<iostream>;3、注意使用名称空间std。

来源:#include <iostream>#include <stdio.h>#include <stdlib.h>using namespace std;int main(){char s[10];gets(s);cout << "Hello, " <<s<< "!"<< endl;return 0;}示例代码----------------------------------------------#include <iostream>#include <string>using namespace std;int main(){string szName;cin >> szName;cout << "Hello, " << szName << "!" << endl;return 0;}-----------------------------------------------------实验题目(共4题, 第2题)标题: 2、求3个数的平均值时限: 1000 ms内存限制: 10000 K总时限: 3000 ms描述:从键盘上输入3个浮点数,求这3个数的平均值。

c++ 字符串比较函数

c++ 字符串比较函数

c++字符串比较函数在C++程序设计中,字符串比较函数扮演着至关重要的角色。

字符串比较是一种用来确定两个字符串之间的大小关系的操作。

它在各种应用场景中都起着重要作用,比如在排序、查找、去重等算法中都需要用到字符串比较函数。

C++标准库提供了多种方法来进行字符串比较。

其中最常见的方法是使用比较运算符"=="、">"、"<"来比较字符串的大小关系。

通过这些运算符,我们可以轻松地比较两个字符串是否相等,或者确定一个字符串是否大于、小于另一个字符串。

这种方法简单直接,适用于大多数场景。

除了比较运算符,C++还提供了一些函数来实现更加复杂的字符串比较操作。

例如,使用`strcmp`函数可以比较两个C风格字符串的大小。

这个函数返回一个整数值,根据返回值的正负可以判断字符串的大小关系。

如果返回值为0,表示两个字符串相等;如果返回值小于0,表示字符串1小于字符串2;如果返回值大于0,表示字符串1大于字符串2。

这个函数在需要对C风格字符串进行比较时非常有用。

除了这些基本的字符串比较函数,C++标准库还提供了一些更加强大的比较函数,例如`std::string::compare`。

这个函数可以比较两个C++风格的字符串对象的大小关系。

和`strcmp`不同的是,`std::string::compare`函数返回一个整数值,而不是简单的正负零。

返回值为0表示两个字符串相等,返回值小于0表示调用对象小于参数字符串,返回值大于0表示调用对象大于参数字符串。

这个函数可以在C++程序中轻松进行字符串比较操作。

通过使用这些字符串比较函数,我们可以避免手动逐个字符比较字符串的麻烦。

这些函数能够提高程序的效率和可读性,使我们的代码更加简洁和易于维护。

然而,我们在使用这些函数时也需注意一些细节,例如比较的是字符还是字符串、字符串的编码方式等。

总之,字符串比较函数在C++程序设计中具有重要而广泛的应用。

C++变位词问题分析

C++变位词问题分析

C++变位词问题分析在《编程珠玑》⼀书的第⼆章提到了⼀个变位词问题,变位词指的是⼀个单词可以通过改变其他单词中字母的顺序来得到,也叫做兄弟单词,如army->mary。

由变位词可以引申出⼏个算法问题,包括字符串包含问题,⽐较两个字符串是否是变位词,以及找出字典中变位词集合的问题。

⼀、字符串包含问题(1) 问题描述:存在字符串1和字符串2,假设字符串2相对较短,如何快速地判定字符串2中的字符都存在于字符串1⾥(假定字符串只包含字母)?(2) 举例:字符串1为ABCDEFGHIJK,字符串2为ABCDE,则字符串1包含字符串2,因为字符串2中包含的字母在字符串1中也都有。

(3) 解决⽅案:思路⼀最直接的思路就是针对字符串2中的每个字符,轮询字符串1进⾏⽐较,看是否在字符串1⾥⾯。

很明显这种的时间效率为O(n*m)。

/*************************************************************************> File Name: test.cpp> Author: SongLee************************************************************************/#include<iostream>#include<string>using namespace std;void Compare(string long_str, string short_str){int i,j;for(i=0; i<short_str.size(); ++i){for(j=0; j<long_str.size(); ++j){if(long_str[j] == short_str[i]){break;}}if(j == long_str.size()){cout << "false" << endl;return;}}cout << "true" << endl;return;}int main(){string l = "ABCDEFGHIJK";string s = "ABCDEF";Compare(l, s);return 0;}思路⼆这⾥由于假定了字符串只包含字母,所以我们可以⽤⼀个额外的数组flag[26]作为26个字符标识位,先遍历长字符串将对应的标识位置1,再遍历短字符串,如果对应的标⽰位都是1,则包含;否则不包含。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Example:
#include <cstring> … if (strcmp(cString1, cString2)) cout << "Strings are not the same."; else cout << "String are the same.";
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
A common method to assign a value to a C-string variable is to use strcpy, defined in the cstring library
Example:
#include <cstring> …
char aString[ 11]; strcpy (aString, "Hello");
strncpy uses a third argument representing the maximum number of characters to copy
Example:
char anotherString[10]; strncpy(anotherString,
aStringVariable, 9);
Hale Waihona Puke Places "Hello" followed by the null character in aString
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 8- 13
A Problem With strcpy
If the null character is lost, the array cannot act like a C-string
Example: int index = 0; while (ourString[index] != '\0') { ourString[index] = 'X'; index++; }
Slide 8- 8
C-string error
This attempt to initialize a C-string does not cause the \0 to be inserted in the array char shortString[ ] = {'a', 'b', 'c'};
0 is interpreted as false
As soon as the characters do not match
strcmp returns a negative value if the numeric code in the first parameter is less
strcmp returns a positive value if the numeric code in the second parameter is less
== Alternative for C-strings
The == operator does not work as expected with C-strings
The predefined function strcmp is used to compare Cstring variables
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 8- 3
8.1
An Array Type for Strings
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 8- 5
C-string Details
Declaring a C-string as char s[10] creates space for only nine characters
The null character terminator requires one space
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 8- 14
A Solution for strcpy
Many versions of C++ have a safer version of strcpy named strncpy
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 8- 9
Don't Change '\0'
Do not to replace the null character when manipulating indexed variables in a C-string
strcpy can create problems if not used carefully strcpy does not check the declared length of the first argument
It is possible for strcpy to write characters beyond the declared size of the array
The null character '\0' is added for you
Another alternative: char shortString[ ] = "abc";
but not this: char shortString[ ] = {'a', 'b', 'c'};
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Chapter 8
Strings and Vectors
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Overview
8.1 An Array Type for Strings 8.2 The Standard string Class 8.3 Vectors
The result is placed in the first argument Example:
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 8- 11
Assignment With C-strings
This statement is illegal:
aString = "Hello"; This is an assignment statement, not an
The loop on the previous slide depended on finding the '\0' character
It would be wiser to use this version in case the '\0' character had been removed int index = 0; while (ourString[index] != '\0' && index < SIZE) { ourString[index] = 'X'; index++; }
Slide 8- 16
strcmp's logic
strcmp compares the numeric codes of elements in the C-strings a character at a time
If the two C-strings are the same, strcmp returns 0
Hi
M o m ! \0 ? ?
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 8- 6
C-string Declaration
To declare a C-string variable, use the syntax: char Array_name[ Maximum_cString_Size + 1];
The Null character is a single character
To declare a C-string variable, declare an array of characters:
char s[11];
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Non-zero values are interpreted as true
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 8- 17
More C-string Functions
The cstring library includes other functions
strlen returns the number of characters in a string int x = strlen( aString);
相关文档
最新文档