#c #justify
Вопрос:
Я новичок в c , и я пытался понять, как бы вы заполнили строку введенной строки Я хотел, чтобы к каждому пробелу добавлялось по одному дополнительному пробелу, пока не закончатся дополнительные пробелы максимальной длиной 30 символов.
Так что, если у меня есть : cout < ;
cin << stringentered ;
Я хочу, чтобы он циклически добавлял пробел, пока не достигнет 30 символов.
Это___ _ _ _ _солнечный день.
Это____ _ _ __ _ _ солнечный___день.
Это_____ _ _ _ _ _ _ _ _ _ солнечный__ _ _день. = это отображение, которое я хочу в конце цикла, которое = 30 символов (_- это пробелы).
Ответ №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 stringn";
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::stringamp; 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::stringamp; 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 << "nn";
}
}
return 0;
}
Для компиляции с C 17.
Комментарии:
1. Ответ выше выглядит как какой-то удивительный код, но я получаю ошибки, когда запускаю его компилятором 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;
}
Комментарии:
1. @Армин Монтиньи псевдо выше