gpt4 book ai didi

c++ - 如果前导0后面的数字是8或9,Scanf不会读取前导0。

转载 作者:行者123 更新时间:2023-12-01 15:10:09 32 4
gpt4 key购买 nike

我有一个非常奇怪的问题,该问题源于我一直在编写的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;
}
尝试输入 12等,我们得到预期的输出 1\n2\n等。这也适用于 0011\n的输入,比如 00044\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不起作用的原因是因为0interpreted作为八进制数字的前缀,而89的数字在八进制中不存在:

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 charactersthat correspond to the base are used.


对于其他数字,您也会得到错误的答案,例如八进制的 010将解析为8。
或者,甚至更好:使用C++代替C。
std::cin >> a[i];

关于c++ - 如果前导0后面的数字是8或9,Scanf不会读取前导0。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63831545/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com