1-0. Compile, execute, and test the programs in this chapter.
#include <iostream> #include <string> using namespace std; int main() { cout<<"input your name:"; string name; cin>>name; const string greet="Hello, "+name+"!"; const string row3="* "+greet+" *"; const string row2Space(greet.size()+2,' '); const string row2="*"+row2Space+"*"; const string row1(row2.size(),'*'); cout<<row1<<endl<<row2<<endl<<row3<<endl<<row2<<endl<<row1<<endl; return 0; }lyj@qt:~/Desktop$ g++ 1-0.cpp -o 1-0
1-1. Are the following definitions valid? Why or why not?
const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";
Ans: "+"两端不能都是字符串字面量或char类型值,只能进行字符串和字符串字面量的连接; const std::string message="hello"+", world"+"!"。
1-2. Are the following definitions valid? Why or why not?
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
Ans:同上。
1-3. Is the following program valid? If so, what does it do? If not, why not?
#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 0;
}
Ans:"{}"的作用,变量作用范围问题。
1-4. What about this one? What if we change }} to };} in the third line from the end?
#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 0;
}
Ans:同上题,将}}修改为};}依然输出a string \n another string;添加的";"是一条空语句。
1-5. Is this program valid? If so, what does it do? If not, say why not, and rewrite it to be valid.
#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 0;
}
Ans:invalid,因为最后一条cout引用了未定义的变量x,x在最内层{}内有效,将最内层{}去除即可。
1-6. What does the following program do if, when it asks you for input, you type two names (for example, Samuel Beckett)? Predict the behavior before running the program, then try it.
#include <iostream>
#include <string>
int main()
{
std::cout << "What is your name? ";
std::string name;
std::cin >> name; ////name1
std::cout << "Hello, " << name<< std::endl << "And what is yours? ";
std::cin >> name;//////name2
std::cout << "Hello, " << name<< "; nice to meet you too!" << std::endl;
return 0;
}
Ans:输入name1,输出Hello, name1 And what is yours?然后要求输入name2,输出Hello, name2;nice to meet you too!