2013-05-30 237 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; 
}