原文地址:http://blog.youkuaiyun.com/dpdldh/article/details/6154220
最近在搞ACM,所以学了一些基本的C++操作。但是发现C++对于字符的操作不像C那么简单。例如,对缓冲区回车符的过滤,string类型的输入等等小问题。所以,笔者通过一些小小的实践,验证了几个常用方法,贴出来献丑~~
(所有程序均在CodeBlock下调试通过)
cin
这个就不多说了,只说它像gets一样,可以过滤掉回车;
例如:
- #include <iostream>
- #include <cstdio>
- using namespace std;
- int main ()
- {
- char a, b;
- cin >> a >> b;
- cout << a << " " << b << endl;
- return 0;
- }
输入:a (回车)
b
输出: a b
把cin改成scanf,则不一样了:
- #include <iostream>
- #include <cstdio>
- using namespace std;
- int main ()
- {
- char a, b;
- scanf("%c%c",&a,&b);
- printf("%c %c/n",a,b);
- return 0;
- }
输入:a (回车)
b
输出:a
说明,scanf无法过滤掉回车;回车符在缓冲区里,被b接收了
cin.get()
参数: cin.get(char c) //接受一个字符
cin.get(char* str, int n) //接受指定个数的字符串(不可接受string类型)
头文件: <iostram>
例子1:
- #include <iostream>
- using namespace std;
- int main(void)
- {
- char a;
- cin.get(a);
- cout << a << endl;
- return 0;
- }
输入: 123456
输出:1
例子2:
- #include <iostream>
- using namespace std;
- int main(void)
- {
- char str[20];
- cin.get(str,19); //19是允许读取的最大字符个数
- cout << str << endl;
- return 0;
- }
输入:123 456 567 (中间两个空格)
输出:123 456 567
注意:cin.get()接受字符串时,可以接受空格,tab;遇到回车结束输入
更多用法请参考: http://www.cplusplus.com/reference/iostream/istream/get/
cin.getline()
参数: cin.getline(char* str, int n) //接受指定长度的字符串,可接受空格,tab;遇到回车结束;不可输入string类型
头文件: <iostream>
例子:
输入:abcde
12345
输出:abcde
12345
更多用法请参考: http://www.cplusplus.com/reference/iostream/istream/getline/
getline()
参数:getline(istream a, string str) //接受一个string类型字符串,可以接收空格并输出
头文件: <string>
例子:
- #include <iostream>
- #include <string>
- using namespace std;
- int main ()
- {
- string str;
- getline (cin,str);
- cout << str << "./n";
- }
输入:sdfsdf 234
输出:sdfsdf 234
更多内容,请参考:http://www.cplusplus.com/reference/string/getline/
cin.ignore()
参数:istream& ignore ( streamsize n = 1, int delim = EOF )
头文件: <iostream>
用法:忽略指定长度字符,或者忽略指定字符;若不加参数,则默认忽略空格或换行
例子:
- #include <iostream>
- #include <cstdio>
- #include <string>
- using namespace std;
- int main ()
- {
- string num, str;
- cin >> str;
- //cin.ignore();
- getline(cin,num);
- cout << str << endl << num << endl;
- return 0;
- }
输入: 1223 (回车)
输出: 1223
若把注释去掉,用上cin.ignore()。则:
输入:1234 6789
输出:1234
6789
说明,把回车给过滤掉了
http://www.cplusplus.com/reference/iostream/istream/ignore/