我的教授给我的任务是使用用户输入的字符串在c++输出中创建一个模式。
程序应以下列方式运行:
Enter a string: ***
***
***
***
***
***
***************
***
***
***
***
***注意:来自用户的输入字符串可以有任意数量的长度或字符。
以下是对该方案的限制:
,
我尝试过多种方法来创建上面的程序,但由于受到限制,我认为这不再可能了,所以我来这里寻求社区的帮助。
下面是我使用循环的代码:
string userInput;
int m = 1, n = 9;
cout<<"\nEnter a three character string: ";
cin>>userInput;
cout<<endl;
while (m <= 6)
{
if (m == 6)
{
cout<<userInput<<userInput<<userInput<<userInput<<userInput<<endl;
m = 1;
n = 13;
while (m <= 5)
{
cout<<setw(n)<<userInput<<endl;
m++;
n--;
}
return 0; //this will finish the execution of the program
}
cout<<setw(n)<<userInput<<endl;
n++;
m++;
}如果用户只输入3个字符串,上述程序就能工作。
我们将非常感谢您的帮助!
对不起,我的英语很差,如果你发现任何错误或错误,请随时编辑和改正。
发布于 2019-10-06 11:27:39
由于需要重复输入字符串或空格的次数是固定的,所以可以手动打印输入的每一次重复。您可以生成空格,它将输入字符串的长度与来自setw的iomanip函数相匹配(参见http://www.cplusplus.com/reference/iomanip/setw/)。
下面是一个例子:
#include <iostream>
#include <iomanip>
int main() {
std::string input = "test";
std::cout << std::setw(input.length() * 3) << input << "\n";
std::cout << input << input << input << "\n";
std::cout << std::setw(input.length() * 3) << input << "\n";
std::cout << "\n";
return 0;
}它产生的输出:
test
testtesttest
test为了避免重复,您可以尝试使用递归。这可能还不是你已经讨论过的一个概念,在这种情况下,最好坚持第一个建议。如果您感兴趣,它可能值得一查,因为它不涉及c++的高级特性。
发布于 2019-10-06 11:27:06
您可以使用所谓的递归函数。这样,您不使用循环,而是递归,您只需调用一次。
#include <iostream>
#include <string>
void coutLine(std::string output) {
std::cout << output << '\n';
}
void recursiveWriter(std::string recursiveInput, int number, int iterator) {
//Correct for even number of lines below and above
number = number - (number % 2);
//You should split this logic in another function, to keep it neat
if (iterator < (number / 2)) {
recursiveInput = std::string(1, ' ') + recursiveInput;
coutLine(recursiveInput);
} else if (iterator > (number / 2)) {
//dividable by 2 triggers the middle line
//iterator should be -1 because one time it has ran by the 'else'
if (iterator - 1 > number / 2) {
recursiveInput = recursiveInput.erase(0, 1);
}
coutLine(recursiveInput);
} else {
//Create the middle line
coutLine(std::string(recursiveInput.length() + 1, '*'));
}
if (iterator < number) {
iterator++;
recursiveWriter(recursiveInput, number, iterator);
}
}当然,我不知道所有的具体要求,但发生了以下情况:
int main() {
int lines = 11;
int iterator = 0;
recursiveWriter("***", lines, iterator);
}
//lines 10 and 11 generates:
***
***
***
***
***
*********
***
***
***
***
***
//lines 12 and 13 generates with input text *****:
*****
*****
*****
*****
*****
*****
************
*****
*****
*****
*****
*****
*****因此,这样,线的数量总是相等的顶部和下面。然而,这一点可以改进。正如前面提到的,可能不会遵循这些要求(您对它们不是很具体)。
发布于 2019-10-06 11:27:47
您可以始终用递归替换迭代。使用现有代码,并将循环转换为递归函数。我会从更换最里面的循环开始,然后找出你的出路。
在我看来,这是递归的糟糕用法。递归对于处理自然递归结构(如树)以及通过将问题分成两部分(如排序)来解决问题非常有用。
https://stackoverflow.com/questions/58256498
复制相似问题