没有输出
No output for 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();
}
只是想知道为什么我没有为此打印出来。提前谢谢。
使用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();
}
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 如何根据单词在文本中出现的概率输出单词