In: Computer Science
Please answer the following questions
1) Suppose the user inputs “Good Morning!” in the console when running the following code.
What will be printed to the console?
char word[100] ;
cout << “Type a word: “;
cin >> word;
cout << word << endl;
2) What is the value of myStr[5] after the following code?
char myStr[100] = “Good!”;
3) Suppose we have a string variable that contains a string with a length of N, what is the index of
the third to the last character in this string?
4) Please fill the two inputs to the substr function so that it will print “morning” to the console.
string myStr = “Good morning Friday!”;
cout<<myStr.substr( ___, ___ )<<endl;
5) I am trying to initialize a c-style string to “chen”. What is the problem of the following code?
char myStr[5] = {‘c’, ‘h’, ‘e’, ‘n’ };
cout<<myStr;
1) When you are using the above code only the first word "Good" will be printed. Cause the cin method will read the letters untill it find a white space(cause char is used as the type). You can view the following images for clarification;
OUTPUT ( when using whitespace):
OUTPUT (without whitespace):
2.The value of mystr[5] will be empty. Cause the string index starting with 0. Hence, there is nothing in the index value 5 in the given string. View the code for the clarity;
OUTPUT:
3. Since the string index ranges from 0 to N-1 if N is the total length of the string. therefor the index of the third to the last character in this string: [2, N-1]
4.myStr.substr(4,9) can be used to print "morning" on screen. See the below code;
OUTPUT:
5.I think there is no problem with the code except you used the quatation style (‘c’) which is not permitted in C++ try using normal ('c'). See the code below;
OUTPUT: