C ++字符串cout字符丢失

时间:2016-06-25 18:19:30

标签: c++ std iostream

这是Visual Studio中的控制台应用程序,所以如果我在cout中调用cout,我想知道发生了什么。它有点工作,但它删除了一个有点奇怪的角色。因此,它会移除stringcoutmain的字符数量。因此它会删除doPrint()函数返回值的尽可能多的字符。

实施例: 如果返回值为1,则输出" AAAAABLLLLLLLLLL" 如果返回值为2,则输出" AAAAALLLLLLLLLL"

#include "stdafx.h"
#include <iostream>

int doPrint()
{
    std::cout << "AAAAA" << std::endl;
    return 1;
}

int main()
{
    std::cout << "BBLLLLLLLLLL" + doPrint() << std::endl;
    int x;
    std::cin >> x;
    return 0;
}

这不是一件大事,但我想知道为什么会这样。 谢谢。

P.S:我知道我应该<<代替+

1 个答案:

答案 0 :(得分:1)

嗯,基本上会发生什么是指针算法和函数调用的指定评估顺序。

"BBLLLLLLLLLL" + doPrint()

所以

"BBLLLLLLLLLL" + 1 

产量

BLLLLLLLLLL

"BBLLLLLLLLLL" + 2 

产量

LLLLLLLLLL

std::cout

它将函数指针算法应用于字符数组文字,&#34;松散&#34; 字符,因为doPrint()产生的内容大于0

+的运算符优先级高于<<,因此首先调用doPrint()并打印AAAAA。所以你的目标

 std::cout << "BBLLLLLLLLLL" + doPrint() << std::endl;

分解为

  1. 致电doPrint()
    1.1。致电std::cout << "AAAAA" << std::endl;
  2. "BBLLLLLLLLLL" + 1
  3. 的结果值调用doPrint()
  4. 致电std::ostream& operator<<(std::otream&, const char*)
  5. 致电std::endl