This is C++, but it is crashed because of atof of null pointer. so I want to cha
ID: 638837 • Letter: T
Question
This is C++, but it is crashed because of atof of null pointer. so I want to change code.
please change correctly.
else if (strcmp(token[0],"CYLINDER")==0)//calculate for cylinder
{
double CYR=atof(token[1]);
double CYH=atof(token[2]);
double CYA=2*Pi*CYR*CYR+2*Pi*CYH*CYR;
double CYV=Pi*CYR*CYR*CYH;
cout<<"CYLNDER radius="<<CYR<<" height="<<CYH<<" surface area="<<CYA;
cout<<" volume="<<CYV<<endl;
}
else if (strcmp(token[0],"CIRCLE")==0)
{
double CIR=atof(token[1]);
double CIA=CIR*CIR*Pi;
double CIC=2*CIR*Pi;
cout<<token[0]<<" radius="<<CIR<<" area="<<CIA<<" circumference="<<CIC<<endl;
}
Explanation / Answer
const int MAX_CHARS_PER_LINE = 50;
const int MAX_TOKENS_PER_LINE = 4;
const char* DELIMITER = " ";
struct Square
{
double length;
};
void squareCalc(double);
int main()
{
cout << endl;
cout << "Description: Calculates area, perimeter, surface area, and volume" << endl;
cout << "of 6 different geometric objects." << endl;
cout << endl;
ifstream fin;
fin.open("geo.txt");
if(!fin.good())
return 1;
char* token[MAX_TOKENS_PER_LINE] = {0};
Square shape;
while(!fin.eof())
{
char buf[MAX_CHARS_PER_LINE];
fin.getline(buf, MAX_CHARS_PER_LINE);
int n = 0;
token[0] = strtok(buf, DELIMITER);
if(token[0])
{
for(n = 1; n < MAX_TOKENS_PER_LINE; n++)
{
token[n] = strtok(0, DELIMITER);
if(!token[n]) break;
} //for
if((strcmp(token[0], "SQUARE") == 0))
{
if(n != 2)
cout << token[0] << " Invalid Object";
else
{
shape.length = atof(token[1]);
squareCalc(shape.length);
} //else
} //if
cout << endl;
} //while
cout << endl;
cout << "Press Enter to continue..." << endl;
cin.get();
return 0;
} //main
void squareCalc(double side)
{
double perimeter;
double area;
perimeter = side * 4;
area = side * side;
cout.setf(ios::fixed|ios::showpoint);
cout << setprecision(2);
cout << "SQUARE side=" << side << " perimeter=" << perimeter;
cout << " area=" << area;
} //squareCalc
Edit & Run
this is the input file:
SQUARE 14.5
RECTANGLE 14.5 4.65
CIRCLE 14.5
CUBE 13
PRISM 1 2 3
SPHERES 2.4
CYLINDER 50 1.23
TRIANGLE 1.2 3.2 3.4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.