Brenden Rodgers
Brenden Rodgers

Reputation: 273

Create string of specific length in C++

For my class, I have to take three strings, then center them.

Here's a link to the problem, and no, I'm not asking for the answer to the problem!
http://www.hpcodewars.org/past/cw3/problems/Prog05.htm

I have everything I need, but I need to create a string of "*" with a specific length. In this case, it needs to be 21 characters long of asterisks, and I don't know how to create that.

I mean, yeah, I can do

string test = "********************"

but it needs to be a different length as it changes.

I have a variable set to how long the string needs to be, but I need to know how to create a string with a specific length, then add in the asterisks.

Code so far:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string line;
    string lines[2];
    int x = 0;
    int maxLength;
    ifstream myfile ("example.txt");

    if (myfile.is_open()) // opening file, setting the strings in the input stream to a variable to use at a later time
    {
        while ( getline (myfile,line) )
        {
            lines[x] = line;
            x++;
        }
        myfile.close();
    }

    if(lines[0].length() > lines[1].length()) //finding the max length;
    {
        maxLength = lines[0].length();
    }else
    {
        maxLength = lines[1].length();
    }
    if(lines[2].length() > maxLength)
    {
        maxLength = lines[2].length();
    }

    maxLength = maxLength + 4;

    cout<<maxLength<<endl;

    return 0;
}

Upvotes: 27

Views: 43753

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

It's much simpler than you think. std::string has a constructor just for this purpose:

#include <string>
#include <iostream>

int main()
{
    std::string s(21, '*');

    std::cout << s << std::endl;

    return 0;
}

Output:

*********************

Upvotes: 61

Related Questions