Hey guys, I've been on here for a while now but just now i registered because I don't know how to fix this after reading numerous posts.Btw you guys helped me a ton this semester.
The code im writing is for a class project. It takes in user input planet name, mass, radius. Then it calculates area, density and gravity(almost). It uses vectors to add, delete, search for by name and sorts by name and also displays all data.
This is the part that gives me an error:
I'm pretty sure its with the logic of the loop. What it does is takes in an input of a user and searches a vector for that input and it displays that information for the user. After that however it gives a segmentation error and quits the program alltogather instead of going back to the menu.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
string Plist::FindPlanet()
{
string X;
bool test=false;
cout << "Enter name of planet to look for: ";
while(!test)
{
cin>>X;
cin.ignore(500,'\n');
for(int i=0; i<P.size();++i)
if(X==P[i].getname()) P[i].Display();
else test = true;
break;
}
}
This is the rest of the code just incase(All of it works except gravity returns inf but that ill fix by passing by refferance.)
As HoneyBoy notes, not returning something when you say you're going to return something is problematic.
The temporary the function (doesn't) return is going to be deconstructed, which means the string class is going to be interpreting some memory as a string object when it's not. That could easily cause your segmentation fault.
If you pay attention to your compiler warnings, this is easily avoided.
Ah thank you very much. This is what it looks like and also void at the decleration and I added an else statement if no such input is found. and the inf for gravity was fixed by changing r to radius in the calculation function. Is it ok to use break like that to get out of the loop?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void Plist::FindPlanet()
{
string X;
bool test=false;
cout << "Enter name of planet to look for: ";
while(!test)
{
cin>>X;
cin.ignore(500,'\n');
for(int i=0; i<P.size();++i)
if(X==P[i].getname())
P[i].Display();
else {cout<<"No such planet found.\n";}
break;
}
}