关于endl的神奇现象

P1603 斯诺登的密码

algobase @ 2023-12-31 11:06:19

#include <bits/stdc++.h>
#define int long long
using namespace std;

int a[6], cnt, num[26] = { 1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 21, 44, 69, 96, 25, 56, 89, 24, 61, 0, 1, 4, 1, 1, 4, 9 };;
char s[1009], cmp[26][10] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "a", "both", "another", "first", "second", "third" };

signed main() {
    ios::sync_with_stdio(false);
    for (int i = 1; i <= 6; i++) {
        cin >> s;
        for (int j = 0; j < 26; j++) {
            if (!strcmp(s, cmp[j])) {
                a[++cnt] = num[j];
                break;
            }
        }
    }
    sort(a+1, a+cnt+1);
    bool flag = false;
    for (int i = 1; i <= cnt; i++) {
        if (flag) {
            printf("%.2d", a[i]);
            break;
        } else {
            if (a[i]) {
>>>>            cout << a[i] << endl;
                flag = true;
            }
        }
    }
    if (!flag) {
        cout << 0;
    }
    return 0;
}

样例输出:425

为了调试程序,此程序输出:

4
25

请各位关注带有 >>>> 的这一行代码

如果将 << endl 删去,上述输出中的换行理应消失,输出 425

但实际输出 254 ,将 endl 换为 '.''-' 甚至 '\n' ,仍先出 25 再输出中间字符最后输出 4

请问各位有没有合理的解释


by yukimianyan @ 2023-12-31 11:07:27

删掉 ios::sync_with_stdio(false);


by algobase @ 2023-12-31 11:08:22

@yukimianyan 谢谢,您能告诉我原因吗


by yukimianyan @ 2023-12-31 11:10:56

因为你关闭 stdio 和 iostream 的同步之后混用他们


by __Tonycyt__ @ 2023-12-31 11:12:25

@algobase

 ios::sync_with_stdio(false);

会关闭同步流,如果加上去就不要 cout,printf 混用


|