1.cin,cin.get(),getchar(),getline(),cin.getline()异同点

113 阅读1分钟

1.cin

读取一个单词或数字(遇空格/换行停止)

#include <iostream>

using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
	string word;
	cout << "请输入一个单词:" << endl;
	cin >> word;//输入"hello world"
	cout << "word = " << word << endl; 
	
	
	return 0;
}

2.cin.get()

读取单个字符(包含空格换行)

#include <iostream>
using namespace std;

int main() {
    char ch;
    cout << "输入一个字符(可包含空格/换行): "<< endl;
    ch = cin.get();        // 逐字符读取
    cout << "ASCII= " << static_cast<int>(static_cast<unsigned char>(ch)) << endl;
    return 0;
}

3.getchar()

C语言版的读一个字符

#include <iostream>
using namespace std;

int main() {
    int ch;
    cout << "输入一个字符(可包含空格/换行): "<< endl;
    ch = getchar();
    cout << "字符:" << char(ch) << endl; 
    cout << "ASCII:" << ch << endl;
    return 0;
}

4.cin.getline()

读整行到char数组

#include <iostream>
using namespace std;

int main() {
    char ch[100];
    cout << "输入一行文字:" << endl;
    cin.getline(ch,99);
    cout << "你输入的是: " << ch << endl;
	return 0;
}

5.getline()

读整行到string,推荐

#include <iostream>
#include <String>
using namespace std;

int main() {
    string name;
    cout << "输入全名" << endl;
	getline(cin,name);
	cout << "你的全名是:" << name << endl; 
	return 0;
}

6.整体区别

函数遇到空格遇到换行符读取范围返回值缓冲区处理使用场景
cin >>停止停止单个数据项引用对象跳过前导空白读取数字、单词
cin.get()继续读取继续读取单个字符字符值(int)不跳过任何字符逐字符处理
getchar()继续读取继续读取单个字符字符值(int)不跳过任何字符C风格字符读取
getline()继续读取停止整行无返回值消费换行符读取完整句子到string
cin.getline()继续读取停止整行无返回值消费换行符读取完整句子到字符数组