Thread: Codeblocks,C++, rand() was not declared.
hopefully posted in right area (sorry if didnt).
hey there. learning c++ c++ dummies all-in-one second edition teach codeblocks (the reason why bought it).
ok, problem error such when building:
here's sourcode (slightly modified books version. added prototype function).code:error; 'rand' not declared in scope
rand() located in getsecretcode() function
missing code wise?code:#include <iostream> #include <sstream> using namespace std; string *getsecretcode(); int main() { string *newcode; int index; ( index = 0; index < 10; index++ ) { newcode = getsecretcode(); cout << newcode << endl; } cout << "all done here" << endl; return 0; } string *getsecretcode() { string *code = new string; code->append("cr"); int randomnumber = rand(); ostringstream converter; converter << randomnumber; code->append(converter.str()); code->append("nq"); return code; }
didn't "#include" ?
rand defined in cstdlib (there no standard c++ random function yet). include:
#include <cstdlib>
have memory leaks in code don't delete created string
should avoid dynamically allocating stuff not needed.
can rewrite this:
code:// long string might expensive copy, use reference void createcopyexpensivestring(string & str) { // dostuff } // short string, cheap copy string createshortstring() { return "shortstring"; } void main() { string str; createcopyexpensivestring(str); cout << str << endl; string str2 = createshortstring(); cout << str2 << endl; } // str , str2 go out of scope here , deleted automatically
Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk [SOLVED] Codeblocks,C++, rand() was not declared.
Ubuntu
Comments
Post a Comment