So I have recently seen the following code optimized for reading numbers.
In this case, I am reading a number T
(denoting the number of strings that will follow).
After this number, T
strings follow. However the code instead of printing strings prints out newline characters.
If I used cin to read T
the code works as expected.
Can some provide some insight into this behavior?
Sample Input
#include <stdio.h>
#include <string>
#include <iostream>
template <typename T>
inline void read(T &f) {
f = 0; T fu = 1; char c = getchar();
while (c < '0' || c > '9') { if (c == '-') { fu = -1; } c = getchar(); }
while (c >= '0' && c <= '9') { f = (f << 3) + (f << 1) + (c & 15); c = getchar(); }
f *= fu;
}
int main() {
std::ios::sync_with_stdio(false);
std::cout.tie(nullptr), std::cin.tie(nullptr);
int T;
read(T);
while (T--) {
std::string s;
std::cin >> s;
std::cout << s << "\n";
}
return 0;
}
Edit: Solution. Do not use std::ios::sync_with_stdio(false);
if you are going to intermix C style reading and C++ style reading.