我正在从使用Python逐渐过渡到使用C ++,但我不知道如何运行任何代码。我正在使用g ++编译器,但是我的函数没有任何结果。
// arrays example
#include <iostream>
using namespace std;
int foo [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; ++n )
{
result += foo[n];
}
cout << result;
return 0;
}
如果我在VSCode中运行此示例,并指定要使用g ++编译器,它将返回:Terminal will be reused by tasks, press any key to close it.
。如果我通过cmd对其进行编译并运行任务,则新的cmd窗口将闪烁,并且没有任何反应。
我找到了g ++文档,其中说明了如何使用g ++进行编译,并显示了以下示例:
#include <stdio.h>
void main (){
printf("Hello World\n");
}
但是我什至不能运行编译器,因为它说
error: '::main' must return 'int'
void main(){
^
如何在cmd或ide终端中打印内容?我不明白。
我相信您以错误的方式使用VSCode。您必须知道默认情况下它没有集成的编译器,但是您需要在命令行中编译源文件并运行可执行文件:
$ g++ hello.cpp
$ ./a.out
您的第一个示例运行正常。检查here
您的第二个示例有错误,因为C ++中没有void main()
。相反,您需要具有
int main() {
return 0;
}
UPDATE
如果运行可执行文件导致打开和关闭窗口,则可以使用以下方法之一来修复该问题:
#include <iostream>
using namespace std;
int main() {
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main() {
do {
cout << '\n' << "Press the Enter key to continue.";
} while (cin.get() != '\n');
return 0;
}
为什么不需要std :: endl?
有些评论暗示正在改变
cout << result;
to
cout << result << endl;
将解决该问题,但是,在这种情况下,当上一行是main函数的最后一行时,实际上并不重要,因为程序的出口会刷新当前正在使用的所有缓冲区(在这种情况下为std::cout
)。