2014-09-25 54 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

相关问题