I'm beginner in C++. Learning mostly from YouTube courses. I was doing the task when I came across the problem which stops me from finishing. I would like to ask for help with the part of code.
#include <iostream> #include <ctime> #include <cmath> #include <cstdio> #include <cstring> #include <fstream> #include <sstream> #include <ostream> using namespace std; int main() { srand(time(0)); ofstream file; cout<<"TASK"<<"\n"; file.open("TASK.txt", fstream::in | fstream::out | fstream::trunc ); if(file.good() == true) { cout<<"TRUE"<<"\n"; char ch[] = {'#','@','*'}; // Array of three chars. for(int i=0; i<10; i++) { for(int j=0; j<10; j++) { file<<ch[rand()%3]; //Random character } file<<endl; } file.seekp(rand()%120); file.put('P'); file.close(); } else cout<<"FALSE"<<"\n"; return 0; }
What I've done:
Opened a file and created array for 3 characters from task description.
Created 2 for loops which write and format the file data.
Found out by using file.seekp(0,file.end) that the amount of characters in file equals 120.
Used knowledge of the amount of characters to file.seekp(rand()%120) which sets position in output sequence to random place.
Used file.put('P') to place character in that place.
Closed file.
What I don't know:
How to get rid of (or do something else to) these 20+ characters to change only these: '#', '@', '*'.
To visualise the problem:
OUTPUT: when it works as intended.
@#*#*##@*@
@@*##*@@@*
@@**@#*@##
#@@*@##P**
****##@@*#
#@#@*@####
**#@#@#@*@
@*#*@###*#
*@###*#@*#
@@*#@@#@@@
When it doesn't work as intended:
@@@#@@@*#*
##*##*@@#*
@@##@#*#*@P
*@@@**###*
##*@*#*@**
**##@#*@**
@###@*#***
@#@**##@@*
#@*###@@@*
@#@#*#*#@#
If I wasn't clear enough I can try to explain more.
Solution (thanks to rustyx)
int r_number = 0;
for(int i=0; i<=120; i++)
{
int r_number2 = rand()%120;
if((r_number2%12)>=10)
{
r_number2 = rand()%120;
}
else r_number=r_number2;
}
Thank you.