【问题标题】:Padout text entered to a specific length adding blank spaces输入到特定长度的填充文本添加空格
【发布时间】:2021-08-04 06:06:22
【问题描述】:

我是一个 c++ 菜鸟,我一直在试图弄清楚如何将输入

如果我有: cout

           cin << stringentered ;

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

今天是__a__晴天。

今天___是___晴天___天。

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

【问题讨论】:

    标签: c++ justify


    【解决方案1】:

    当然有很多可能的解决方案。

    我将根据以下算法举一个例子

    • 从字符串中提取所有单词
    • 计算字符串中所有单词的字符总和
    • 其余部分可用于空间。计算一下
    • 然后我们将可用空间除以单词之间的间隙数
    • 整数除法可能有余数,我们会平均分配

    一个(许多)可能的解决方案可能如下所示:

    #include <string>
    #include <sstream>
    #include <algorithm>
    #include <iterator>
    #include <vector>
    #include <numeric>
    
    // Maximum filed width
    constexpr size_t MaxWidth = 30u;
    
    int main() {
    
        // Instruction for the user
        std::cout << "\nPlease enter a string\n";
        if (std::string stringEntered{}; std::getline(std::cin, stringEntered)) {
    
            // Only do something if the string is shorter than the maximum filed width (and, if the string is not empty)
            if (stringEntered.length() < MaxWidth and not stringEntered.empty()) {
    
                // We want to extract words (and spaces)
                std::istringstream iss(stringEntered);
    
                // Get all words (not white spaces) from the string
                std::vector words(std::istream_iterator<std::string>(iss), {});
    
                // Get accumulated length of all words
                size_t wordsLength = std::accumulate(words.begin(), words.end(), 0, [](size_t i, const std::string& s) { return i + s.length(); });
    
                // Get the number of separators
                size_t numberOfSeparators = (words.empty() ? 0u : words.size() - 1u);
    
                // How much place do we have for spaces?
                size_t spaceToDistribute = MaxWidth - wordsLength;
    
                // For an equal distribution, we need to know, how many spaces to print
                size_t separatorLength = spaceToDistribute / numberOfSeparators;
                int separatorLengthRest = static_cast<int>(spaceToDistribute % numberOfSeparators);
    
                // Now, output all words and spaces
                // Some ruler
                std::cout << std::string(MaxWidth, '.') << '\n';
    
                // Print result
                for (const std::string& word : words) {
    
                    // Calculate number of spaces. Do an even distribution
                    size_t numberOfSpaces = separatorLength + (((separatorLengthRest--) > 0) ? 1 : 0);
    
                    // No spaces after last word
                    if (word == words.back()) numberOfSpaces = 0;
    
                    // Show word and spaces
                    std::cout << word << std::string(numberOfSpaces,' ');
                }
    
                std::cout << "\n\n";
            }
        }
    
        return 0;
    }
    

    需用 C++17 编译。

    【讨论】:

    • 上面的答案看起来像一些很棒的代码,但是当我在 C++17 编译器上运行它时出现错误,我不知道为什么。我在下面发布了一些伪代码,也许有帮助。
    【解决方案2】:
    #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;
    
    }
    

    【讨论】:

    • @Armin Montigny 伪以上
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 2011-09-29
    • 1970-01-01
    • 2010-09-16
    • 2012-11-08
    • 1970-01-01
    相关资源
    最近更新 更多