C++的输入输出操作cin
和cout
使用起来比scanf
和printf
要方便,因为它在输入和输出时不用指明数据类型,系统会自动判断。但是cin
和cout
也有它的缺点,就是输入输出较scanf
和printf
而言要慢,因此很多人写代码时会加上句ios::syn_with_stdio(false)
来提高cin
和cout
的效率,原先一直听人说这样写可能会引发问题,但却不知道具体是什么问题,今天终于遇到了一个由ios::sync_with_stdio(false)
引发的问题。
先不讨论下面代码的实际应用,我们知道如果输入的是1 2 3 4 5 6
,那么输出的应该是2 3 4 5 6
,请注意我这里并非漏了1
,而是因为1
被getchar
“吃掉”了。这段代码在VS2019中的运行结果和我们预想的一样,但是当到了gcc编译器环境下,输入1 2 3 4 5 6
再按回车之后不会有任何的输出。
#include<bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
int num[20];
int index = 0;
while(getchar() != '\n')
cin>>num[index++];
for(int i = 0;i<index;i++)
cout<<num[i]<<" ";
}
那么是不是说明上述代码的功能就无法在gcc中实现了呢?其实可以用cin.get()
函数代替getchar()
函数,如下面的代码所示。
#include<bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
int num[20];
int index = 0;
while(cin.get() != '\n')
cin>>num[index++];
for(int i = 0;i<index;i++)
cout<<num[i]<<" ";
}
cin.get()
和getchar()
的功能都是从输入缓冲区中读取一个字符,因此当想用cin
和cout
作为输入输出函数时,尽量用cin.get()
,而不要用getchar()
。