首页 > 解决方案 > 输入到特定长度的填充文本添加空格

问题描述

我是一个 c++ 菜鸟,我一直在试图弄清楚如何将输入 <30 字符的字符串行填充到特定长度集。我想在每个空白处添加一个额外的空格,直到额外的空格用完最大长度 30 个字符。

所以如果我有: cout << "Enter String" ;

           cin << stringentered ;

我希望它循环添加一个空格,直到它达到 30 个字符。

它__is__a__晴天。

它___是___a___晴天___天。

它____是____a_____晴____天。= 这是我想要在循环结束时显示的 = 30 个字符(_ 是空格)。

标签: c++justify

解决方案


#include <iostream>
#include <string>
#include <cctype>
#include <cstring>

using namespace std;

//Function prototypes
void padOutSpaces(string validInput);

int main()
   {
// ask for input
// initialInput = fetchInput(); 

// check that the input is not greater than 30 characters – if it is, display an error message
// initialInput = checkValidityAndAskAgain(initialInput); // haven't checked if this is valid syntax

// take input of 30 or less and fill in spaces
//padOutSpaces(initialInput);
  }

 //This will fetch the initial input from the user, any length is acceptable

 // string fetchInput() {
 //ask for input
  }

 //Check that the param is not greater than 30 characters – if it is, display an error message and asks for intput again

// string checkValidityAndAskAgain(String ) {
// while NOT string length > 30
// we ask again
    
// return value
 }

//Take input of 30 or less and fill in spaces

//void padOutSpaces(string validInput) {
// int desiredLength = 30;

// while validInput length is less than 30 aka desired length variable at the beginning of the func
// <code here>
    
    // loop through each char (up till validInput length) so we can check for spaces
    // <code here>
        
        // check if/whether at a space yet AND whether our string length is still under desired length
        // <code here>
            
            // add a space at the next index so that it now appears after the "found" space
            // <code here>
            
            // push index 1 forward forward again so it skips the next char which is the one we just inserted
            // <code here>

    //force a break out of loop. 

cout << "*********** Checked input length and it's now 30 :D" << endl;
cout << validInput << endl;

}

推荐阅读