繁体   English   中英

在C ++中创建特定长度的字符串

[英]Create string of specific length in C++

对于我的班级,我必须采取三个字符串,然后居中。

这是问题的链接,不,我不是要问问题的答案!
http://www.hpcodewars.org/past/cw3/problems/Prog05.htm

我有我需要的一切,但我需要创建一个具有特定长度的“*”字符串。 在这种情况下,它需要21个字符长的星号,我不知道如何创建它。

我的意思是,是的,我能做到

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

但它需要变化的长度不同。

我有一个变量设置为字符串需要多长时间,但我需要知道如何创建具有特定长度的字符串,然后添加星号。

代码到目前为止:

#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;
}

这比你想象的要简单得多。 std::string只有一个构造函数用于此目的:

#include <string>
#include <iostream>

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

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

    return 0;
}

输出:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM