歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++中字符串I/O

C++中字符串I/O

日期:2017/3/1 10:08:11   编辑:Linux編程

可以使用cout和插入操作符<<來輸出string對象,這和處理其他類型的數據是一樣的;

可以使用cin和提取操作符>>時,方式和其他數據一樣,但要注意:>>會忽略最初的空白字符,並在遇到更多的空白字符時停止讀入!

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

如果要想讀取一整行,可以使用getline()函數,注意:這個getline()不是成員函數!

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

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

Copyright © Linux教程網 All Rights Reserved