cout没有输出?

时间:2014-02-24 23:24:49

标签: c++ visual-studio-2010 division cout

#include<iostream>
#include<iomanip>
#include <math.h>


using namespace std;

int doIt(int a){
    a=a/1000;
    return a;
}

void main(){
    int myfav= 23412;
    cout<<"test: "+doIt(myfav);
    cin.get();
}

只是想知道为什么我没有为此打印出来。 提前谢谢。

4 个答案:

答案 0 :(得分:2)

使用C ++流,您应该cout << "test: " << doIt(myfav),而不是一起尝试+。我不确定<<+是否优先,但无论您是添加到流还是字符串文字,这都不会很好。

答案 1 :(得分:2)

void main()不是main函数的有效签名(但VS会识别它,它不符合标准)。它应该是int main()

您无法使用+将整数插入字符串。您需要使用std::ostreamoperator<<的提取运算符。你所拥有的将导致指针运算(将doIt的结果添加到const char*的地址,这是未定义的行为)。

std::cout是缓冲输出流。由于您没有刷新缓冲区,因此程序有可能在您能够看到输出之前(在控制台关闭之前)结束。将输出行更改为以下之一:

std::cout << "test:  " << doIt(myFav) << std::endl; // flush the buffer with a newline

std::cout << "test:  " << doIt(myFav) << std::flush; // flush the buffer

总而言之,你所拥有的将会编译,但根本不会做你想要的。

答案 2 :(得分:2)

我想指出的很少。第一个返回主函数void main()的类型应为int main()

请勿使用using namespace std;了解更多详情,请访问Why is "using namespace std" considered bad practice?

最后你的代码中的问题是你无法使用+将整数插入到一个字符串中,你必须再次提取运算符,即<<

#include<iostream>
#include<iomanip>
#include <math.h>

//using namespace std;

int doIt(int a)
{
    a=a/1000;
    return a;
 }
int main()
{
    int myfav= 23412;
    std::cout<<"test: "<<doIt(myfav)<<"\n";
    std::cin.get();
    return 0;


}

答案 3 :(得分:0)

语句

中的此表达式"test: "+doIt(myfav)
cout<<"test: "+doIt(myfav);

表示向指针添加一些整数值,指向字符串文字“test:”的第一个字符。结果语句输出获得的指针值。

如果要将函数返回的整数值转换为std :: string类型的对象,则可以使用operator +。例如

cout<<"test: "+ to_string( doIt(myfav) );

为此,您需要包含标题<string> 考虑到函数main在C / C ++中应该有返回类型int。最好使用标题<cmath>而不是标题

恢复我所说的所有内容,我将展示程序的外观

#include<iostream>
#include <string>

inline int doIt( int a ) { return a / 1000; }


int main()
{
    int myfav = 23412;

    std::cout << "test: " + std::to_string( doIt( myfav ) ) << std::endl;

    std::cin.get();
}