c++ - getchar_unlocked() VS scanf() VS cin

标签 c++ scanf

这三个输入函数在编程语言中有什么区别。 他们的输入方式是否不同?

1.getchar_unlocked()

 #define getcx getchar_unlocked

 inline void inp( int &n ) 
 {
    n=0;
    int ch=getcx();int sign=1;
    while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getcx();}

    while(  ch >= '0' && ch <= '9' )
            n = (n<<3)+(n<<1) + ch-'0', ch=getcx();
    n=n*sign;
  }   

2.scanf("%d",&n)

3.cin>>n

输入整数时,哪一项花费的时间最少?

我在 c++ 中使用这些头文件,其中所有 3 个大小写都在 c++ 中运行;

  #include<iostream>
  #include<vector>
  #include<set>
  #include<map>
  #include<queue>
  #include<stack>
  #include<string>
  #include<algorithm>
  #include<functional>
  #include<iomanip>
  #include<cstdio>
  #include<cmath>
  #include<cstring>
  #include<cstdlib>
  #include<cassert>

最佳答案

需要考虑的两点。

  1. getchar_unlocked 在 Windows 中已弃用,因为它是 getchar() 的线程不安全版本。

  2. 除非速度因素太需要,否则尽量避免getchar_unlocked

现在,就速度而言。

    getchar_unlocked > getchar

因为在 getchar_unlocked 中没有输入流锁定检查,这使得它不安全。

    getchar > scanf

因为 getchar 读取输入的单个字符,它是 char 类型,而 scanf 可以读取 c 中可用的大多数原始类型。

    scanf > cin (>> operator)

因为检查这个 link

所以,终于

getchar_unlocked > getchar > scanf > cin

关于c++ - getchar_unlocked() VS scanf() VS cin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9052757/

相关文章:

c++ - 在没有 QApplication 的情况下使用 Qts QXmlSchemaValidator

c - 将数据存储到多维数组中

c - 如何使用 sscanf() 在 C 中解析 URL?

c - 使用 scanf 分隔冒号时出现问题

c - 如何使用任意数量的 scanf() 格式说明符?

c - fscanf 无法从多维矩阵文件中读取正确的 double

c++ - 为什么我收到此错误 "access violation writing location"?

c++ - 打印与数组中的值一样多的星星

Java 到 C++ 命名空间和#include

c++ - 在Qt中保存下载的文件