cout << string(pattern.length() - i - 1, ) 我不明白这一行


//code to write a pyramid with input from user
#include <iostream>
#include <string>
using namespace std;
int main()
{
string pattern {};
cout << "Enter string: ";
getline(cin, pattern);
int i {}, j {}, k {};
for(i = 0; i < pattern.length(); ++i) {
cout << string(pattern.length() - i - 1, ' '); // display leading spaces
for(j = 0; j < i + 1; ++j) // display left side
cout << pattern.at(j);
for(k = i - 1; k >= 0; k--) // display right side
cout << pattern.at(k);
cout << endl;
}
}

此行:

cout << string(pattern.length() - i - 1, ' '); // display leading spaces

使用带计数的字符串构造函数和char。结果是包含char重复计数次数的字符串。例如

cout << string(4, 'a');

将导致:

aaaa

它返回一个由pattern.length() - i - 1空格组成的字符串。

fill (6) string (size_t n, char c);

(6( fill构造函数
用字符c.的n个连续副本填充字符串。

string::string-C++引用

cout << string(pattern.length() - i - 1, ' '); // display leading spaces

这一行将显示在每一行上开始填充图案之前所需的空间。假设你的图案长度是3。因此,在第一行,它将显示一个空格等于3-0-1=2的字符串,然后打印图案。类似地,它将在迭代的剩余部分继续。


这里string()是一个构造函数,它可以接受2个参数。语法为-

string (size_t n, char c);

第一个是要使用字符c构建的字符串的字符串长度,第二个是要用于构建字符串的字符本身。


如果你不习惯使用它,你可以考虑这行代码做一些等效于以下代码的事情-

for(j = 0 ; j < pattern.length() - i - 1 ; j++) // prints spaces in each iteration 
cout << ' ';

如果要打印某个字符一定次数而不是循环,则可以使用string()方式。它将使您的代码更短。

int main()
{
string pattern {};       // initialises pattern with empty string
cout << "Enter string: ";
getline(cin, pattern);   // takes user input into pattern
int i {}, j {}, k {};    
// We will loop for pattern.length() times
for(i = 0; i < pattern.length(); ++i) { 
// In each iteration, first print required number of leading spaces
// So, string(pattern.length() - i - 1, ' ') will initialise a string with required number of spaces and print it
cout << string(pattern.length() - i - 1, ' '); // display leading spaces
// Once spaces are printed, we print i+1 characters from pattern starting from 0th index of pattern
for(j = 0; j < i + 1; ++j) // display left side
cout << pattern.at(j);

// We will now print i characters from pattern, this time starting from i-1th index
for(k = i - 1; k >= 0; k--) // display right side
cout << pattern.at(k);
cout << endl;
}
}

例如。假设输入是CCD_ 9。因此输出将如下-

*        // i=0 : 1st loop prints 5-0-1=4 spaces, 2nd loop prints 0 to 0+1=1 characters from pattern, i.e, * and 3rd loop doesn't run on this iteration
*-*       // i=1 : 1st loop prints 5-1-1=3 spaces, 2nd loop prints 0 to 2 characters, ie, *- and 3rd loop prints (1-1)th index till 0th index of pattern which is 0th index,i.e, *
*-*-*      // i=2 : 1st loop prints 5-2-1=2 spaces, 2nd loop prints 0 to 3 characters, ie *-* and 3rd loop prints (2-1)th index till 0th index, ie 1st and 0th index of pattern,i.e, -*
*-*-*-*     // Similar process as above
*-*-*-*-*    // Similar process as above

希望这现在有意义:(

相关内容

最新更新