为什么在输出到标准输出的末尾会出现%的百分比,而在使用endl时却没有?

问题描述 投票:0回答:1

为什么在这个输出的最后有一个尾部的%? 我试过刷新流(不是endl),但是当我用调用endl结束流时,它就把%去掉了。 如果有任何帮助,我将非常感激。

template<class T>
void print_collection(T * t){
        for(int i = 0; i < t->size()-1; ++i){
                cout << t->at(i) << ", ";
        }
        std::cout<< t->at(t->size() -1);
        std::cout<<flush;
}

int main(){
        int n_A = 5;
        int A[] = {2, 3, -2, 34, -29};

        vector<int> vec(A, A + n_A);
        sort(vec.begin(), vec.end());

        print_collection(&vec);
        return 0;
}

OUTPUT
-29, -2, 2, 3, 34%  

这里有更多关于编译器的信息,我使用的是macOS 10.15.4。

g++ -Wall -std=c++11 array.cpp -o array

g++ Information:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 11.0.3 (clang-1103.0.32.59)
Target: x86_64-apple-darwin19.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin  
c++ stream cout
1个回答
0
投票

重复的问题。 谢谢 @WBuck!

@Kevin说:当一个程序的(非空)输出没有包含尾部的换行符时,zsh会添加那个颜色反转的%来表示,并在打印提示符之前移动到下一行;它通常比bash的行为更方便,只是在输出结束的地方开始命令提示符。

用C语言在终端的printf输出中得到一个奇怪的百分号。


0
投票

我注意到一个类似的问题,很久以前。

这有可能是来自你的输出shell,而不是程序本身的输出。所以在你做任何重大改变之前,先看看这个问题。

根据你正在做的事情--防止出现这种情况的一个好办法是在你的打印函数的输出中添加一个新行。

Newline to print function example

© www.soinside.com 2019 - 2024. All rights reserved.