C++中字符串I/O


可以使用cout和插入操作符<<来输出string对象,这和处理其他类型的数据是一样的;

可以使用cin和提取操作符>>时,方式和其他数据一样,但要注意:>>会忽略最初的空白字符,并在遇到更多的空白字符时停止读入!

  1. // String.cpp : Defines the entry point for the console application.  
  2. //  
  3.  
  4. #include "stdafx.h"  
  5. #include<iostream>  
  6. #include<conio.h>  
  7. #include<string>  
  8.  
  9. int main(int argc, char* argv[]) 
  10.     using namespace std; 
  11.     string line; 
  12.     cout<<"Enter a line ofinput :"
  13.     cin>>line; 
  14.     cout<<"Output :"
  15.     cout<<line; 
  16.     cout<<endl; 
  17.     return 0; 

 

如果要想读取一整行,可以使用getline()函数,注意:这个getline()不是成员函数!

  1. // String.cpp : Defines the entry point for the console application.  
  2. //  
  3.  
  4. #include "stdafx.h"  
  5. #include<iostream>  
  6. #include<conio.h>  
  7. #include<string>  
  8.  
  9. int main(int argc, char* argv[]) 
  10.     using namespace std; 
  11.     string line; 
  12.     cout<<"Enter a line ofinput :"
  13.     getline(cin,line); 
  14.     cout<<"Output :"
  15.     cout<<line; 
  16.     cout<<endl; 
  17.     return 0; 

 

注意:此时未忽略前面的空白符!

相关内容