#include<iostream>
using namespace std;
int main()
{
int i=1,len;
char ch[26][26],ch2;
cout<<"enter string: "<<endl;
for(i=0;;i++)
{
cin>>ch[i];
len++;
if(getchar()=='n')
break;
}
int n,j;
cout<<"enter size: "<<endl;
cin>>n;
int k;
for(i=0;i<=n;i++)
{
for(j=0;j<=n;j++)
{
if(i==0||i==n||j==0||j==n)
{
cout<<"*";
}
else
cout<<" ";
if(i==((n/2)-2)&&j==((n/2)-2))
{
for(k=0;k<len;k++)
{
cout<<ch[k]<<endl;
cout<<"*";
}
}
}
cout<<"n";
}
}
该程序在正方形内显示字符串,但正方形的星形图案变得混乱,尤其是最右边的列 任何帮助将不胜感激
由于您在代码中没有提供太多细节,因此我从头开始使用新代码,这就是我想出的:
#include <iostream>
#include <vector>
为您的字符串使用向量,并动态调整大小(如果我在您的代码中输入超过 26 个单词怎么办?提示:分段错误!
using std::vector;
using std::string;
using std::cout;
using std::cin;
using std::endl;
最好避免使用using namespace std;
。只需导入您真正需要的东西。
int main() {
vector<string> strings;
您肯定希望在此处使用字符串,而不是char
数组。
cout << "Enter string: ";
输入提示后不要换行!(作为一个Linux用户,我个人讨厌它)
for(;;) {
您不需要这里的变量i
,只需运行一个无限循环(尝试重新排列它,如果您可以避免无限循环,while(getchar() != 'n')
更不言自明。
string s;
cin >> s;
strings.push_back(s);
正如pstrjds在评论中建议的那样,如果可以的话,请使用getline()
。
if(getchar() == 'n')
break;
就像我说的,尝试以while
的条件重新制定。
}
unsigned int n, i, j;
cout << "Enter size: ";
cin >> n;
// assuming strings.size() < n
unsigned int empty_lines_around_text((n - strings.size()) / 2);
由于您要打印位于正方形内的单词,因此您必须显示少于半个正方形的* (...) *
行:实际上是半个正方形减去要打印的字符串数量的一半。
// first horizontal row of stars
for(j = 0; j < n; ++j)
cout << '*';
cout << endl;
正方形的上侧。
for(i = 1; i < empty_lines_around_text; ++i) {
cout << '*';
for(j = 1; j < n - 1; ++j) {
cout << ' ';
}
cout << '*' << endl;
}
要打印的第一行,其中没有字符串的行。
//here we do the actual printing of the strings
for(i = 0; i < strings.size(); ++i) {
string s = strings[i];
// once again, assuming the size of each string is < n
unsigned int empty_chars_around_string((n - s.size()) / 2);
cout << '*';
for(j = 0; j < empty_chars_around_string; ++j)
cout << ' ';
cout << s;
for(j = empty_chars_around_string + s.size() + 1; j < n - 1; ++j)
cout << ' ';
cout << '*' << endl;
}
这是有问题的部分。就像空行一样,我们需要一个变量来包含我们必须在字符串之前打印多少空格,以便它看起来居中(变量empty_chars_around_string)。
我们打印那么多空格,字符串,我们在行尾*
之前用空格完成行,这是数组中的每个字符串。
for(i = empty_lines_around_text + strings.size() + 1; i < n; ++i) {
cout << '*';
for(j = 1; j < n - 1; ++j) {
cout << ' ';
}
cout << '*' << endl;
}
在打印字符串后,我们用空行完成正方形。
// last horizontal line of '*' (we close the square)
for(j = 0; j < n; ++j)
cout << '*';
cout << endl;
。啊,我们关闭广场。
return 0;
}
现在,这段代码并不完美,有很多重构和优化要做,但它最大限度地利用了C++功能。
这是一个包含整个代码的粘贴箱。
当使用字符串运行时,输出Hello friends
和大小12
:
************
* *
* *
* *
* *
* hello *
* friends *
* *
* *
* *
* *
************
主要问题在于:
for(k=0;k<len;k++)
{
cout<<ch[k]<<endl;
cout<<"*";
}
在这里,当您放置输入字符串时,您还会输入一个新行并以星号 (*) 开头。您不仅不会将最后一个星号放在输入字符串的行上,而且也不会在那里更新j,它仍然大于 0,当代码继续使用for(j=0;j<=n;j++)
j 时,j已经有了换行符 + 星号的剩余值。
尝试:
for( k = 0; k<len; k++ )
{
cout << ch[k];
j += strlen( ch[k] );
}
这样j将更新到输入字符串的最后一个位置。
PS:对于常见的编码实践,将开头的len初始化为0。