So I was coding a program that takes the length of a given string, then loop through it until it is divisible by 16. I don't know what's going on in the program but it spits this error out:
terminate called after throwing an instance of std::length_error' what(): basic_string::_M_replace_aux
I expect an output of the text padded with 0's and the length being divisible by 16
Heres the code
#include <iostream>
#include <string.h>
using namespace std;
int check(string usrinp) {
if (usrinp.length() % 16 != 0) {
for (int i = 0; i < usrinp.length(); i ) {
if (usrinp.length() % 2 != 0) {
usrinp.append(15 - usrinp.length(), '0');
}
else {
usrinp.append(16 - usrinp.length(), '0');
}
}
}
cout << usrinp;
return 0;
}
int main(){
check("1");
}
CodePudding user response:
It is not very clear what question is asking about. So I implemented two interpretations of your question.
First variant, when you have to make a multiple of 16 by repeating a string, then you just have to use LCM (Least Common Multiple), your target string size is equal target_size = LCM(original_string.size(), 16)
.
Second solution is when you have to pad a string to multiple of 16. Then your resulting size is equal to target_size = (original_string.size() 15) / 16 * 16
.
#include <numeric>
#include <iostream>
#include <string>
std::string RepeatToMultiple(std::string const & s, size_t k) {
size_t const cnt = std::lcm(s.size(), k) / s.size();
auto r = s;
for (size_t i = 1; i < cnt; i)
r = s;
return r;
}
std::string PadToMultiple(std::string s, size_t k, char fill = '0') {
s.resize((s.size() k - 1) / k * k, fill);
return s;
}
int main() {
std::string s = "abcde_";
std::cout << "Original: (size " << s.size() << ") " << s << std::endl;
auto r = RepeatToMultiple(s, 16);
std::cout << "Repeated till multiple of 16: (size " << r.size() << ") " << r << std::endl;
auto r2 = PadToMultiple(s, 16);
std::cout << "Padded to multiple of 16: (size " << r2.size() << ") " << r2 << std::endl;
}
Output:
Original: (size 6) abcde_
Repeated till multiple of 16: (size 48) abcde_abcde_abcde_abcde_abcde_abcde_abcde_abcde_
Padded to multiple of 16: (size 16) abcde_0000000000
CodePudding user response:
What you want is to calculate your padding correctly:
int pad = 16 * (str.length() / 16 1) - str.length();
Example1:
length of string = 4
then required pad = 12
16 * (4 / 16 1) - 4 gives 12. Don't be mistaken by (4 / 16), it'll result in 0 for integer division.
Example2:
length of string = 37 then required pad = 11
16 * (37 / 16 1) - 37 gives 11.
Then you can use whatever function you require to append to the string.
str.append(pad, '0');