c++ - 输入到特定长度的填充文本添加空格
问题描述
我是一个 c++ 菜鸟,我一直在试图弄清楚如何将输入 <30 字符的字符串行填充到特定长度集。我想在每个空白处添加一个额外的空格,直到额外的空格用完最大长度 30 个字符。
所以如果我有: cout << "Enter String" ;
cin << stringentered ;
我希望它循环添加一个空格,直到它达到 30 个字符。
它__is__a__晴天。
它___是___a___晴天___天。
它____是____a_____晴____天。= 这是我想要在循环结束时显示的 = 30 个字符(_ 是空格)。
解决方案
#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;
}
推荐阅读
- python - 如何通过在后台检测到按键来打破无限循环?
- c - 使用结构从另一个函数调用变量
- c++ - 在带有 LLD 的 Windows 10 上使用 Clang
- r - 避免覆盖 data.table 函数中的现有列
- mysql - mysql:外键不起作用?存在不应该存在的记录
- javascript - vue.js:如何从数组中的对象进行计算?
- r - 如何运行 Chow 测试以检查面板数据中随时间推移的结构性中断?
- php - 为表单中的函数命名
- geoserver - 使用 UWP MapControl 和离线 GeoServer 切片
- android - 使用两种方法的回调在 NonActivity 类和 Fragment 之间不起作用