Reputation: 10773
I'm startin development on a junk file generator, but for some reason if I use a large number it will beep infinitely until the file is finished, I'm thinking there is a \a character somewhere in the ascii table, or it's overflowing and causes an error beep. Anyone wanna explain why this thing is screaming at me?
#include <string>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <time.h>
#include <windows.h>
#define print cout<<
using namespace std;
int numberof,i;
char charvalue;
string charlist,filename;
int main()
{
srand (time(NULL));
print "What do you want the name of your file to be?(with a .txt extension)\n";
getline(cin,filename);
print "\nHow many characters do you want?\n";
cin>>numberof;
for(numberof>0;numberof!=0;numberof--)
{
i = rand() % 255 + 32;
charvalue=i;
charlist=charlist+charvalue;
print charlist;
}
ofstream writefile(filename.c_str());
writefile<<charlist;
writefile.close();
ShellExecute(NULL, "open", filename.c_str(), NULL, NULL, SW_SHOWNORMAL);
return 0;
}
Seems like at this point the characters are coming out alright in the end, but it only writes 1/4 of them to the text file. Anyone know why?
Upvotes: 0
Views: 369
Reputation: 263360
I'm thinking there is a \a character somewhere in the ascii table
Yes, it is in position 7, I believe.
Also, this:
for(numberof>0;numberof!=0;numberof--)
should be this:
for(; numberof > 0; numberof--)
The condition goes in the middle, and you do not need any initialization, hence the empty statement at the beginning of the for-loop.
Also, the printable ASCII characters only range from 32 to 126, so you should write:
i = rand() % 95 + 32;
Also, the following is extremely inefficient, as it generates a new string object every time:
charlist=charlist+charvalue
Do this instead:
charlist.push_back(charvalue);
Upvotes: 2
Reputation: 18288
Remove the print charlist
so you're not printing the bell characters out.
Upvotes: 0
Reputation: 19623
The fact that you're printing the entire charlist every time means as fast as you can means that as soon as you generate at least a couple \a
characters in the output string (the odds of which aren't too bad), you will get nothing but incessant beeping.
Upvotes: 1
Reputation: 490728
i = rand() % 255 + 32;
You probably want this to be something like:
i = rand() % (255-32) + 32;
You also really want to get rid of this:
#define print cout<<
As it stands, when (not if) whoever is grading your homework decides to kill you, he (she?) will almost certainly be found not guilty of murder on the grounds that it was self defense.
Upvotes: 7