+ 1
getting segmentation fault sometimes
#include <iostream> #include <string> #include <ctime> #include <cstdlib> using namespace std; int main() { srand(static_cast <unsigned int> (time(0))); int numchoices; cout<<"How many things is there to pick from?\n"; cin>>(numchoices); if(numchoices < 1) { cout<<"Error: Cannot allocate null number of choices;\nClosing program...\n"; return 0; } cout<<"\n alright then enter the "<<(numchoices)<<" things.\n"; string choices[(numchoices)-1]; for(int x = 0;x<numchoices;x++) { cout<<":"<<x+1<<" "; cin>>choices[x]; } cout<<"Alright i have picked;\n"; int pick = (rand() % numchoices-1) +1; cout<<pick<<": "; cout<<choices[pick-1]<<endl; return 0; }
8 ответов
+ 1
You allocate numchoices-1 choices but use numchoices.
+ 1
Oh whoops my bad, thanks Stefan
+ 1
Also your calculation for pick is a bit confusing. Just do rand() % numchoices
+ 1
No prob :-)
+ 1
I usually account for number guesses being 1-10 rather than 0-9 due to arrays, made a mistake
+ 1
thanks for the help
+ 1
No prob @ all 😎
+ 1
;)