2014-09-25 24 views
0

我正在做一個項目,我需要讓電腦打印12天的聖誕歌詞。我想到了一個想法,我做了一個FOR循環並重復了12次。每一天的一天運營商變化「++」這是我的意思:如何將一個數字「綁定」到一串單詞/短語,以便我可以在循環中調用它?

int main() 
{ 

    string Print = first = 1; //Here I want first to become a number so that I can call it up in FOR loop. 

    cout << "On the first day of Christmas, \nmy true love sent to me\nA partridge in a pear tree.\n" << endl; 


    for(int loop = 0; loop <= 12; loop++)//This part is a simple for loop, it starts at 0 and goes to 12 until it stops. 
    { 
    cout << "On the " << (1,2,3,4,5,6,7,8,9...12) << " day of Christmas,\nmy true love sent to me\n" << endl; HERE!!!! 

這裏是我在哪裏有問題。我希望這些數字可以用字符串來表示這一天。在x = 1中將調用「First」,然後我可以通過使用「x ++」來移動數字,這會導致x = 2,然後它會說「Second」..一直到12。我可以解決這個問題? }

+0

您是否考慮過使用['std :: map'](http://en.cppreference.com/w/cpp/container/map)或['std :: vector'](http:// en。 cppreference.com/w/cpp/container/vector)? – 2014-09-25 23:59:19

+0

使用帶有字符串內容的數組或向量 - 畢竟,這就是它們的用途! – Conduit 2014-09-26 00:01:12

+0

不,我還沒有(但很快!),我不確定如何使用這些,因爲我對C++還是比較新的,但我一定會去查看它。謝謝你的提示! – Shico75 2014-09-26 00:01:40

回答

1

這涉及一個簡單但重要的程序部分,稱爲數組。我不想直接給你答案 - 你需要始終使用這些(或類似結構),並且練習它們的使用和理解它們是非常重要的。讓我們使用陣列上打印「Hello World」的一個簡單的程序:

#include <iostream> 
#include <string> 

int main() { 
    std::string words[2]; //make an array to hold our words 
    words[0] = "Hello";  //set the first word (at index 0) 
    words[1] = "World";  //set the second word (at index 1) 
    int numWords = 2;  //make sure we know the number of words! 

    //print each word on a new line using a loop 
    for(int i = 0; i < numWords; ++i) 
    { 
     std::cout << words[i] << '\n'; 
    } 
    return 0; 
} 

你應該能夠找出如何使用類似的策略,讓你問上面的功能。 Working Ideone here

+0

是的!這是一個類似於我的想法的程序。 – Shico75 2014-09-26 00:16:50

相關問題