如果前导 0 之后的数字是 8 或 9,则 Scanf 不会读取前导 0
Scanf does not read leading 0s if digit after leading 0s are 8 or 9
我有一个非常奇怪的问题,它源于我一直在编写的 C++11 程序的错误。
见以下代码:
long long a[1000];
int main(int argc, char * argv[]) {
for(long long i = 0; i < 300; ++i) {
scanf("%lli", &a[i]);
std::cout << a[i] << std::endl;
}
return 0;
}
尝试输入 1
、2
等,我们得到了预期的输出 1\n
、2\n
等。这也适用于像 001
这样的输入,我们得到 1\n
,0004
,我们得到 4\n
。
然而,当前导零之后的数字是 8 或 9 时,scanf()
首先读取前导零,然后读取后面的数字。
例如:
输入:0009
,输出:000\n9\n
.
输入:08
,输出0\n8\n
。
输入:00914
,输出00\n914\n
。
我做了一些测试,对于这些情况,似乎 scanf()
首先读取前导零,其余数字留在缓冲区中,在第二个 运行 的循环。
有人可以提示发生了什么事吗?
我正在使用 XCode 11.3.7 并使用 Clang C++11 进行编译。 (我没有搞乱项目设置)
提前致谢!!!
使用 %lld
而不是 %lli
。
%i
不起作用的原因是因为 0
是 interpreted 作为八进制数的前缀,而数字 8
和 9
八进制不存在:
d
Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
i
Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters
that correspond to the base are used.
对于其他数字,您也会得到错误的答案,例如010
八进制将被解析为 8.
或者,甚至更好:使用 C++ 而不是 C。
std::cin >> a[i];
我有一个非常奇怪的问题,它源于我一直在编写的 C++11 程序的错误。
见以下代码:
long long a[1000];
int main(int argc, char * argv[]) {
for(long long i = 0; i < 300; ++i) {
scanf("%lli", &a[i]);
std::cout << a[i] << std::endl;
}
return 0;
}
尝试输入 1
、2
等,我们得到了预期的输出 1\n
、2\n
等。这也适用于像 001
这样的输入,我们得到 1\n
,0004
,我们得到 4\n
。
然而,当前导零之后的数字是 8 或 9 时,scanf()
首先读取前导零,然后读取后面的数字。
例如:
输入:0009
,输出:000\n9\n
.
输入:08
,输出0\n8\n
。
输入:00914
,输出00\n914\n
。
我做了一些测试,对于这些情况,似乎 scanf()
首先读取前导零,其余数字留在缓冲区中,在第二个 运行 的循环。
有人可以提示发生了什么事吗?
我正在使用 XCode 11.3.7 并使用 Clang C++11 进行编译。 (我没有搞乱项目设置)
提前致谢!!!
使用 %lld
而不是 %lli
。
%i
不起作用的原因是因为 0
是 interpreted 作为八进制数的前缀,而数字 8
和 9
八进制不存在:
d
Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
i
Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that correspond to the base are used.
对于其他数字,您也会得到错误的答案,例如010
八进制将被解析为 8.
或者,甚至更好:使用 C++ 而不是 C。
std::cin >> a[i];