没有输出

No output for cout?

本文关键字:输出      更新时间:2023-10-16
#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();
}

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

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

void main()不是

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

不能使用 + 将整数插入到字符串中。 您需要使用 std::ostream 的提取运算符:operator<< 。 你所拥有的将导致指针算术(将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

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

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

不要使用 using namespace std; 有关更多详细信息,请访问为什么"使用命名空间 std"被认为是不好的做法?

最后,代码中的问题您不能使用 + 将整数插入到字符串中,您必须提取运算符,即 又<<

#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;

}

此表达式在语句中"test: "+doIt(myfav)

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

意味着向指向字符串文本"test:"的第一个字符的指针添加一些整数值。 结果,语句输出获得的指针值。

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

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

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

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

#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();
}