使用cin.get()和cin.getline()的输入时候,往往会因为前一步输入结束后,输入换行,导致下一步的输入出现错误,这时由于键盘缓冲区的问题导致的。
1. cin.get()
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main() {
char str[100];
char s;
//测试cin.get();
/*
输入:abcd + 换行('\n')
输出:10
abcd
*/
cin.get(str, 100);
scanf("%c", &s); // 从缓冲区读入换行符'\n',换行符的ASCII码值为10。
cout << "输出:" << endl;
cout << int(s) << endl; // 输入字符对应的ascII码值
cout << str << endl;
return 0;
}
输入输出:
2. cin.getline()
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main() {
char str[100];
char s;
// 测试cin.getline();
/*
输入:abcd + 换行('\n')
a
输出:97
abcd
*/
cin.getline(str, 100); // 执行完毕后会将缓冲区的换行符删除
scanf("%c", &s);
cout << "输出:" << endl;
cout << int(s) << endl; // 输入字符对应的ascII码值
cout << str << endl;
return 0;
}
输入输出:
3. 将scanf换成cin输入则不会发生上述问题
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main() {
char str[100];
char s;
//测试cin.get();
/*
输入:abcd + 换行('\n')
输出:10
abcd
*/
cin.get(str, 100);
cin >> s;
cout << "输出:" << endl;
cout << int(s) << endl; // 输入字符对应的ascII码值
cout << str << endl;
return 0;
}
输入输出:
先用cin输入,再用再用cin.get()或cin.getline()输入都会产生上述问题
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main() {
char str[100];
char s;
//若先用cin输入再用cin.get()或cin.getline()输入则都会出现上述问题,输入完cin后会直接跳过cin.get()或cin.getline()
/*
输入:a + 换行('\n')
输出:97
*/
//cin一样
scanf("%c", &s);
//cin.get()一样
cin.getline(str, 100); // 读入scanf输入后键盘缓冲区剩下的换行符,执行结束。
cout << "输出:" << endl;
cout << int(s) << endl; // 输入字符对应的ascII码值
cout << str << endl;
return 0;
}
输入输出:
参考文章:
C++ cin.get用法(详解版)