C++中字符串I/O
C++中字符串I/O
可以使用cout和插入操作符<<来输出string对象,这和处理其他类型的数据是一样的;
可以使用cin和提取操作符>>时,方式和其他数据一样,但要注意:>>会忽略最初的空白字符,并在遇到更多的空白字符时停止读入!
- // String.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include<iostream>
- #include<conio.h>
- #include<string>
- int main(int argc, char* argv[])
- {
- using namespace std;
- string line;
- cout<<"Enter a line ofinput :";
- cin>>line;
- cout<<"Output :";
- cout<<line;
- cout<<endl;
- return 0;
- }
如果要想读取一整行,可以使用getline()函数,注意:这个getline()不是成员函数!
- // String.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include<iostream>
- #include<conio.h>
- #include<string>
- int main(int argc, char* argv[])
- {
- using namespace std;
- string line;
- cout<<"Enter a line ofinput :";
- getline(cin,line);
- cout<<"Output :";
- cout<<line;
- cout<<endl;
- return 0;
- }
注意:此时未忽略前面的空白符!
评论暂时关闭