0

randomization of location

I ask to help to write the code which would add a random number of zeros, a random letter, and then zeros that the total numbers and letters of digits was 8. For example: 3 zeros were output - output a letter - output 4 zeros p.s. I tried to do string zero [...]; zero [rand ()% 7], but I did not figure out how to save the value, and then output the remaining zeros https://code.sololearn.com/cj1mCtAamKH2/?ref=app

20th Sep 2018, 12:57 PM
Komunre
Komunre - avatar
8 Answers
+ 1
Hmm, works for me. Here: https://code.sololearn.com/c6K1v0qTWrg2/?ref=app Edit: Okay, spotted the mistake in your code. What you are currently doing is outputting a random amount of zeros, then a random letter and afterwards eight zeros. This is because you output the string twice. Once after its initialization, when there is a random amount of zeros inside, and once after the letter, when it consists of eight zeros. You don't use push_back(), that's why the letter is not inserted in the string and it will be filled with eight zeros.
21st Sep 2018, 7:38 AM
Shadow
Shadow - avatar
+ 1
I hope I understood the question correctly. Here is what I'd probably do: //initialize string with random amount of zeros between 0 and 7 std::string s( rand() % 8, '0' ); //add random letter (small) s.push_back( static_cast<char>( rand() % 26 + 97 ) ); //get the current length of the string std::size_t length = s.length(); //fill up to eight characters with '0' s.append( 8 - length, '0' ); //now you can output the string I didn't actually test this, so I hope that it is okay and runs. For reference on the methods I used: http://www.cplusplus.com/reference/string/string/
20th Sep 2018, 4:44 PM
Shadow
Shadow - avatar
+ 1
thank you! it is a pity that with random numbers it does not work out that way
21st Sep 2018, 10:33 AM
Komunre
Komunre - avatar
0
this code outputs 8 zeros in any case after the letter, I also need that the maximum number of characters in the line does not exceed 8
21st Sep 2018, 6:38 AM
Komunre
Komunre - avatar
0
Do you mean you want to fill the string with random numbers instead of zeros? That could be solved using Ascii again.
21st Sep 2018, 10:36 AM
Shadow
Shadow - avatar
0
I modified my previous code, I think this should do the trick, just some ASCII magic: https://code.sololearn.com/cRioJQLq8L3z/?ref=app It has become pretty long by now, if you want to use it multiple times in your code, I'd suggest you to outsource it into a function.
21st Sep 2018, 10:46 AM
Shadow
Shadow - avatar
21st Sep 2018, 11:57 AM
Komunre
Komunre - avatar
0
I thought of something like this as a start: https://code.sololearn.com/cHGy5t2O0Lg5/?ref=app
21st Sep 2018, 1:05 PM
Shadow
Shadow - avatar