什么是在不打开整数的情况下读取每一行的最有效方法?

ido*_*ooo 1 c++

什么是在不打开整数的情况下读取每一行的最有效方法?我每行只有一个整数,即:num.txt

100
231 
312
...
Run Code Online (Sandbox Code Playgroud)

在我的程序中,我使用while循环读取它;

int input = 0;
while(cin >> input)
{        
// Assignment
}
Run Code Online (Sandbox Code Playgroud)

我曾经time a.out <num.txt在Linux上阅读过它,事实证明,读取1亿个数字大约需要15秒(用户时间)。所以我想知道是否有更好的方法来减少用户时间?

先感谢您!

sha*_*ats 5

int input = 0;
ios_base::sync_with_stdio(false); 
//Add this statement and see the magic!
while(cin >> input)
{        
// Assignment
}
Run Code Online (Sandbox Code Playgroud)

要使其超快(不建议用于作业!),请使用getchar_unlocked()

int read_int() {
  char c = getchar_unlocked();
  while(c<'0' || c>'9') c = gc();
  int ret = 0;
  while(c>='0' && c<='9') {
    ret = 10 * ret + c - 48;
    c = getchar_unlocked();
  }
  return ret;
}

int input = 0;
while((input = read_int()) != EOF)
{        
// Assignment
}
Run Code Online (Sandbox Code Playgroud)

Vaughn Cato的答案很好地说明了这一点。