cin与scanf一样也是遇见空格、制表符、换行符就会分割字符串,所以它无法输入带有空格的字符串。
借用了CS生的代码:
第一段代码:
#include <iostream>
using namespace std;
int main() {
char str[20];
cout<<"Enter a string by cin.get():";
cin.get(str, 20); // input: C C++
cout<<"received by cin.get():"<<str<<endl;
cout<<"Enter a string by cin.getline():";
cin.getline(str, 20);
cout<<"received by cin.getline():"<<str<<endl;
return 0;
}
运行结果:
Enter a string by cin.get():C C++
received by cin.get():C C++
Enter a string by cin.getline():received by cin.getline():
第一段代码cin.getline(str, 20);行遇到空格了,所以啥也没输入。
第二段代码:
#include <iostream>
using namespace std;
int main() {
char str[20];
cout<<"Enter a string by cin.get():";
cin.getline(str, 20); // input: C C++
cout<<"received by cin.get():"<<str<<endl;
cout<<"Enter a string by cin.getline():";
cin.get(str, 20); // input: C C++
cout<<"received by cin.getline():"<<str<<endl;
return 0;
}
运行结果:
Enter a string by cin.get():C C++
received by cin.get():C C++
Enter a string by cin.getline():C C++
received by cin.getline():C C++
实际上,cin.get() 和 cin.getline() 都会遇到换行符并停止读取。问题出在对输入缓冲区的处理上。
在使用 cin.get() 读取字符串时,它会读取指定数量的字符,并将换行符留在输入缓冲区中。这意味着下一个输入操作(例如 cin.getline())会继续从换行符开始读取,导致输入错误。
换行符在输入中起到两个作用:
-
实现换行操作:当我们在终端或命令行中输入换行符时,它会告诉程序我们已经输入完一行内容,可以进行下一行的输入。
-
留在输入队列中:换行符会留在输入缓冲区中,等待下一个输入操作。这意味着,如果我们使用 cin.get() 或 cin.getline() 来读取字符串,它们会遇到换行符并停止读取。这是因为默认情况下,cin.get() 和 cin.getline() 都会读取输入缓冲区中的字符,直到遇到换行符为止。