C++中使用ios::sync_with_stdio(false)可能引发的问题

  C++的输入输出操作cincout使用起来比scanfprintf要方便,因为它在输入和输出时不用指明数据类型,系统会自动判断。但是cincout也有它的缺点,就是输入输出较scanfprintf而言要慢,因此很多人写代码时会加上句ios::syn_with_stdio(false)来提高cincout的效率,原先一直听人说这样写可能会引发问题,但却不知道具体是什么问题,今天终于遇到了一个由ios::sync_with_stdio(false)引发的问题。
  先不讨论下面代码的实际应用,我们知道如果输入的是1 2 3 4 5 6,那么输出的应该是2 3 4 5 6,请注意我这里并非漏了1,而是因为1getchar“吃掉”了。这段代码在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()的功能都是从输入缓冲区中读取一个字符,因此当想用cincout作为输入输出函数时,尽量用cin.get(),而不要用getchar()

发布了172 篇原创文章 · 获赞 81 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_43074474/article/details/105416077