如何将数字"Bind"到一串单词/短语中,以便我可以循环调用它?

How to "Bind" a number to a string of words/phrase so that I can call it up in a loop?

本文关键字:短语 循环 调用 我可以 一串 Bind 数字 单词      更新时间:2023-10-16

我正在做一个项目,需要让电脑打印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 menA 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 men" << endl;  HERE!!!!

这就是我的问题所在。我想把这些数字串起来,以表示当天。在x=1中,我会调用"First",然后我可以使用"x++"将数字向上移动,这将导致x=2,然后它会说"Second"。。一直到12岁。有人知道我该如何解决这个问题吗?}

这涉及到编程中一个简单但重要的部分,称为数组。我不想直接给你答案——你需要一直使用这些(或类似的结构),练习和理解它们非常重要。让我们使用打印"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;
}

你应该能够想出如何使用类似的策略来获得你上面要求的功能。我在这里工作。