2013-05-30 236 views
2

我刚开始读加速C++,我试图通过练习来上班的时候,我碰到这一个:编写程序打印“Hello,world!”程序

0-4. Write a program that, when run, writes the Hello, world! program as its output.

于是我想出了这个代码:

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

using namespace std; 

int main() 
{ 
    cout << helloWorld << endl; 

    cin.get(); 
    return 0; 
} 

void helloWorld(void) 
{ 
    cout << "Hello, world!" << endl; 
} 

我不断收到错误'helloWorld' : undeclared identifier。我认为我应该做的是为helloWorld做一个函数,然后调用该函数的输出,但显然这不是我所需要的。我也试过把helloWorld()放在主要位置,但那也没有帮助。任何帮助是极大的赞赏。

+2

'helloWorld()'需要_declared_才可以使用。 –

+1

我不清楚作业的内容。他们希望你编写一个打印“你好,世界!”的程序或者打印“代码”为“Hello,World!”的程序风格的程序?这两者有微妙的不同。 –

+4

@NikBougalis:从引用的文本开始,它应该显然是后者。 – Grizzly

回答

7

你不是真正调用helloWorld功能的任何地方。如何:

int main() 
{ 
    helloWorld(); // Call function 

    cin.get(); 
    return 0; 
} 

注意:如果要在定义之前使用它,还需要在顶部声明函数原型。

void helloWorld(void); 

这是working sample

+3

你需要先声明helloWorld()。 – siritinga

+0

@siritinga - 啊好的电话,我添加了一个工作小提琴,err Ideone链接.. –

+0

哦,我看到..我只是想,如果因为问题想让我写一个程序“你好,世界!”作为我需要把它放在cout之间的输出。那么,至少我现在知道如何调用函数。 :) 非常感谢你。 – iKyriaki

3

要调用一个函数,你需要:

  • 其使用
  • 之前提供一个声明,按照它的名字有一对括号,即使它不具有任何参数。
  • 提供一个返回值以便在表达式中使用它。

例如:

std::string helloWorld(); 

int main() 
{ 
    cout << helloWorld() << endl; 
    ... 
} 

std::string helloWorld() 
{ 
    return "Hello, world!"; 
} 
+3

呃...考虑到'helloWorld'是一个无效函数,即使是括号。 –

+0

你是对的 - 我错过了第三个错误。固定在上面。 –

0
hellwoWorld(); 

代替cout << helloWorld << endl;

11

我读的课本习题的方式是,它要你写一个程序,打印出另一 C++程序到屏幕上。现在,您需要用cout语句和"" s包围的文字字符串来执行此操作。例如,您可以从

cout << "#include <iostream>" << std::endl; 
+0

令人惊讶的是阅读iKyriaki的评论[在“接受”的答案(http://stackoverflow.com/a/16842835/2932052);) – Wolf

0

在您的主函数中,helloWorld不是已声明的变量。

你想要hellowWorld是一个字符串,其内容是hello world程序。

0

根据你使用的编译器,你可能需要把helloWorld函数放在你的main之前,像这样。

void helloWorld(void) 
{ 
    ..... 
} 
int main() 
{ 
    ..... 
} 

我使用视觉工作室,我不得不这样做....

0

你并不真正需要的底部定义了HelloWorld功能。像这样的东西应该这样做。

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

using namespace std; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    //cout will output to the screen whatever is to the right of the insertion operator, 
    //thats the << to it's right. 
    //After "hello world" the insertion operator appears again to insert a new line (endl) 
    cout << "hello world" << endl; 

    //cin.get() waits for the user to press a key before 
    //allowing the program to end 
    cin.get(); 
    return 0; 
}