您的位置:首页 > 编程语言 > C语言/C++

C++基础---string类的operator<</operator>>/getline

2015-09-03 18:23 591 查看

1. string类的operator<< /operator>> /getline

1.1 std::operator<< (string)

原型: ostream& operator<< (ostream& os, const string& str);

说明: 用于输出操作,将字符串插入流。

代码示例:

#include <iostream>

#include <string>

using namespace std;
int main()
{
string str = "Hello world!";
cout<<str<<endl;
system("pause");
return 0;
}
=>Hello world!


1.2 std::operator>> (string)

原型: istream& operator>> (istream& is, string& str);

说明: 用于输入操作,从流中提取字符串。

代码示例:

#include <iostream>

#include <string>

using namespace std;
int main()
{
string str;
cout<<"Put in : ";
cin>>str;
cout<<"Put out: "<<str<<endl;
system("pause");
return 0;
}
=>Put in : Hello world
Put out: Hello


1.3 std::getline (string)

原型: istream& getline (istream& is, string& str, char delim);

说明:从流中提取一行字符串,存入str直到划界字符delim(delimitation)被发现。

代码示例:

#include <iostream>

#include <string>

using namespace std;
int main()
{
string str;
cout<<"Put in : ";
char delimitation = '!';
getline(std::cin, str, delimitation);
cout<<"Put out: "<<str<<endl;
system("pause");

return 0;
}
=>Put in : Hello world!
Put out: Hello world


原型:istream& getline (istream& is, string& str);

说明:从流中提取一行字符串,存入str直到划界字符delim(delimitation)”\n“换行符被发现。

代码示例:

#include <iostream>

#include <string>

using namespace std;
int main()
{
string str;
cout<<"Put in : ";
getline(std::cin, str);
cout<<"Put out: "<<str<<endl;
system("pause");

return 0;
}
=>Put in : Hello world!
Put out: Hello world!


参考文献:

[1] 网络资源:

http://www.cplusplus.com/reference/string/string/operator%3C%3C/

http://www.cplusplus.com/reference/string/string/operator%3E%3E/

http://www.cplusplus.com/reference/string/string/getline/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: