我正在做一个项目,我需要让计算机打印 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。任何人都知道如何我可以解决这个问题吗?
最佳答案
这涉及一个简单但重要的编程部分,称为数组。我不想直接给你答案——你需要一直使用这些(或类似的结构),练习它们的使用和理解它们非常重要。让我们使用打印“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 .
关于c++ - 如何将 "Bind"数字转换为一串单词/短语,以便我可以在循环中调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26049984/