C++接收含空格、tab的字符串

一.摘要

  本菜鸡昨晚做题的时候发现不会接收含空格和tab的字符串,固有本随笔;

二.cin.get(char *str, int count)

示例代码:

 1 /*cin.get()接收含空格、tab的字符串*/
 2 #include<iostream>
 3 #include<string>
 4 using namespace std;
 5 int main() {
 6     char c[1000];    //不能直接 char *c,不能使用未初始化的变量
 7     cin.get(c, 1000);
 8     string word(c);    //使用c创建字符串
 9     cout << "字符数组c:	" << c << endl;
10     cout << "字符串word:	" << word << endl;
11     system("pause");
12     return 0;
13 }

运行结果:

 

三.getline(std::istream &io,string &str);

示例代码:

 1 /*getline接收含空格、tab的字符串*/
 2 #include<iostream>
 3 #include<string>
 4 using namespace std;
 5 int main() {
 6     string s;
 7     getline(cin, s);
 8     cout << "字符串s:	" << s << endl;
 9     system("pause");
10     return 0;
11 }

运行结果:

四.总结

  c的 gets() 就不介绍了,听说有啥bug,其他的方法应该还有,后面再更吧~

原文地址:https://www.cnblogs.com/chasemeng/p/12901372.html