C++中如何接收输入的字符串

  注意到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在内的字符.

posted @ 2013-04-30 18:05  微温的便当  阅读(4441)  评论(3)    收藏  举报