std :: cout行为不一致 [英] Inconsistent std::cout behavior

查看:110
本文介绍了std :: cout行为不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎 std :: cout 在打印多件东西时不能始终如一地工作,如以下两个示例所示。我以为它可能与缓冲区刷新有关,但是即使在测试示例中添加了许多 std :: flush ,它也没有任何区别。

I seems std::cout does not work consistently in printing multiple things, as shown in the following two examples. I thought it might related to buffer flush but it made no difference even if I add a number of std::flush in the test example.

#include <cstdlib>                                                                                                   
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>

void test(const std::string& f1);

int main(void) {
    std::string a = "a";
    std::cout << a <<  a << a << std::endl; 
    // Then I got aaa on the screen, which is as expected. 

    test("inputfile");
    // The input file contains one character: "a" 
    // after running the test I got only one "a" on the screen
    // even though the string is repeated three times in the cout statement, as in the previous case
    return 0;
}

void test(const std::string& f1){
    std::ifstream ifile;
    ifile.open(f1);

    for(std::string line; std::getline(ifile, line); ) {
        std::cout << line <<  line << line << std::endl;
    }
    ifile.close();
}

我希望看到

aaa     
aaa 

,但实际输出为

aaa 
a

我用它来编译

g++ -g -std=c++11 -o test test.cpp

g ++的版本为5.2.0。

The version of g++ is 5.2.0.

推荐答案

我觉得Mark Ransom的评论指出了问题所在。您可以通过以二进制模式打开文件并打印编码字符的整数值来验证该假设。

I have a feeling the comment by Mark Ransom points out the problem. You can verify that hypothesis by opening your file in binary mode and printing the integer values that encode the characters.

void test(const std::string& f1){
    std::ifstream ifile;
    ifile.open(f1, std::ifstream::binary);

    int ch;
    while ( (ch = ifile.get()) != EOF )
    {
       // Print the integer value that encodes the character
       std::cout << std::setw(2) << std::setfill('0') << std::hex << ch << std::endl;
    }
    ifile.close();
}

如果输出为

61
0d
0a

并且您的平台不是Windows,那么您获得的输出将很有意义。

and your platform is not Windows, then the output your are getting would make sense.

从文件中读取的行包含字符' a' 0x61 )和'\r' 0x0d )。

The line read from the file contains the characters 'a' (0x61) and '\r' (0x0d).

回车符('\r')导致该行写在上一个输出的顶部。

The carriage return character ('\r') causes the line to be written on top of the previous output.

这篇关于std :: cout行为不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆