注意到C++课本中关于接收用户输入的字符串都是用的字符数组, 看着极为不舒服, 所以试了一下直接用string变量接收, 发现没问题, 代码如下:
1 #include<isotream>
2 #include<string>
3 using namespace std;
4
5 int main()
6 {
7 string strTest;
8 cout<<"输入字符串"<<endl;
9 cin>>strTest;
10 cout<<strTest;
11 return 0;
12 }
注意引入string库函数
另外注意到上面直接输入遇到空格就终止输入了, 所以要想保留空格,可以修改代码如下
1 #include<isotream>
2 #include<string>
3 using namespace std; 4 5 int main() 6 { 7 string strTest; 8 cout<<"输入字符串"<<endl; 9 getline(cin, strTest); 10 cout<<strTest; 11 return 0; 12 }
使用getline函数即可读取包括space在内的字符.