用C++解决问题第十版 第8章字符串和向量
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++语言概述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语言中可以使用多种方法来定义、初始化和操作字符串。
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++字符串

第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++程序设计》习题解答第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

如果题目是 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语言中常用的字符串处理技巧,帮助读者更加熟练地处理和操作字符串。
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
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++字符串和函数答案第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++解决问题第十版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。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 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);