Returning a string stream (char*) - c++

My professor wants me to output the "area" from calculateArea as a char/string. I'm not sure exactly what he means, but maybe some of you might understand.
#include <iostream>
#include "math.h"
#include <cmath>
#include <sstream>
#include <string>
using namespace std;
const char& calculateArea(double diameter, double chord)
{
double length_1, length_2, angle; //This creates variables used by the formula.
angle = acos( (0.5 * chord) / (0.5 * diameter) ); //This calculates the angle, theta, in radians.
cout << "Angle: " << (angle * 180) / 3.14159 << "\n"; //This code displays the angle, currently in radians, in degrees.
length_1 = (sin(angle)) * 6; //This finds the side of the triangle, x.
cout << "X: " << length_1 << " inches "<< "\n"; //This code displays the length of 'x'.
length_2 = (0.5 * diameter) - length_1; /*This code finds the length of 'h', by subtracting 'x' from the radius (which is half the diameter).*/
cout << "h: " << length_2 << " inches" << "\n"; //This code displays the length of 'h'.
double area = ((2.0/3.0) * (chord * length_2)) + ( (pow(length_2, 3) / (2 * chord) ) ); /*This code calculates the area of the slice.*/
ostringstream oss;
oss << "The area is: "<< area << " inches";
string aStr = oss.str();
cout << "Debug: "<< aStr.c_str() << "\n";
const char *tStr = aStr.c_str();
cout << "Debug: " << tStr << "\n";
return *tStr;
//This returns the area as a double.
}
int main(int argc, char *argv[]) {
double dia, cho; //Variables to store the user's input.
cout << "What is your diameter? "; //
cin >> dia; // This code asks the user to input the diameter & chord. The function will calculate
cout << "What is your chord? "; // the area of the slice.
cin >> cho; //
const char AreaPrint = calculateArea(dia, cho); //Sends the input to the function.
cout << AreaPrint; //Prints out the area.
return 0;
}
I get the output as this though:
What is your diameter? 12
What is your chord? 10
Angle: 33.5573
X: 3.31662 inches
h: 2.68338 inches
Debug: The area is: 18.8553 inches
Debug: The area is: 18.8553 inches
T
I need to figure out how to return the string tStr points to. If you don't get what I'm saying, sorry, not really sure what the professor is asking for.

You are returing a char reference not a string.
(the *tStr says 'give me the contents of the pointer')
A more correct version of what you are trying is:
const char* calculateArea(double diameter, double chord)
and
return tStr; // no 'content of'
But this is still bad: the string returned is "out of scope" when aStr goes out of scope, so you really need to return a copy of the characters or just return the string itself (and let the std lib worry about the copy for you)
const string calculateArea(double diameter, double chord)
...
return aStr;

Related

VS2022 code analysis error using uninitialized memory C++ [duplicate]

This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Calling function with variable that is being initialized [duplicate]
(1 answer)
Closed 5 months ago.
Here are the errors on the following code after the VS2022(v143) upgrade:
Could someone please suggest what is wrong here and how to fix it?
//Cricle properties problem
#include <iostream>
using namespace std;
float Qradius(float diameter)
{
float radius = diameter / 2;
return radius;
}
float Warea(float radius)
{
float area = (radius *radius) *3.14;
return area;
}
float Ecircumference(float diameter)
{
float circumference = 3.14 * diameter;
return circumference;
}
float Rarclength(float arcangle, float circumference)
{
float arclength = (circumference *arcangle) / 360;
return arclength;
}
int main()
{
float diameter, arcangle;
float area, circumference, arclength, radius;
cout << "Type the diameter ";
cin >> diameter;
cout << "Type the arcangle ";
cin >> arcangle;
cout << "The radius of the circle is " << Qradius(diameter) << endl;
cout << "The area is " << Warea(radius) << endl;
cout << "The circumference is " << Ecircumference(diameter) << endl;
cout << "The arc length is " << Rarclength(arcangle, circumference) << endl;
}
I solved the warnings and explained why they were coming up in the comments in the code. Also do not use using namespace std;
#include <iostream>
float Qradius(float diameter)
{
float radius = diameter / 2;
return radius;
}
float Warea(float radius)
{
// if no f is specified, the compiler assumes it is a double
// the warning tells you that it converts a double to float
// which could lead to loss of data (C4244)
float area = (radius *radius) * 3.14f;
return area;
}
float Ecircumference(float diameter)
{
// same as aboth
float circumference = 3.14f * diameter;
return circumference;
}
float Rarclength(float arcangle, float circumference)
{
float arclength = (circumference *arcangle) / 360;
return arclength;
}
int main()
{
float diameter, arcangle;
// area and arclength are unused (C4101)
float /*area,*/ circumference, /*arclength,*/ radius;
std::cout << "Type the diameter ";
std::cin >> diameter;
std::cout << "Type the arcangle ";
std::cin >> arcangle;
// radius and circumference is never set
// and later used without setting any value (C6001)
radius = Qradius(diameter);
circumference = Ecircumference(diameter);
std::cout << "The radius of the circle is " << radius << std::endl;
std::cout << "The area is " << Warea(radius) << std::endl;
std::cout << "The circumference is " << circumference << std::endl;
std::cout << "The arc length is " << Rarclength(arcangle, circumference) << std::endl;
}

error: expected a ';', bug in Intellisense when building?

I got an error in Visual Studio 2019, when building and using IntelliSense at the same time, which said that it expected a ';' (CODE: E0065 and the error is supposed to be on line 9), I am extremely confused because this is my first time getting an error like this when defining functions because it is also my first time defining functions in c++, I really don't know where I could be missing a semi colon. The program doesn't run.
#include <iostream>
using namespace std;
int main() {
const double pi{3.14159};
double calc_area_circle(double radius) {
return pi * (radius * radius);
}
void area_circle() {
double radius{};
cout << "Enter the radius of the circle: ";
cin >> radius;
cout << "The area of the circle with radius " << radius << " is " << calc_area_circle(radius) << endl;
}
return 0;
}
If any one could clear this up for me, I would really appreciate it.
Nesting of function definition (defining functions inside another functions) is not allowed in C++ unless you use lambda functions.
Put the function definitions outside the function
#include <iostream>
using namespace std;
const double pi{3.14159};
double calc_area_circle(double radius) {
return pi * (radius * radius);
}
void area_circle() {
double radius{};
cout << "Enter the radius of the circle: ";
cin >> radius;
cout << "The area of the circle with radius " << radius << " is " << calc_area_circle(radius) << endl;
}
int main() {
return 0;
}
or convert them to lambda function
#include <iostream>
using namespace std;
int main() {
const double pi{3.14159};
const auto calc_area_circle = [&](double radius) -> double {
return pi * (radius * radius);
};
const auto area_circle = [&]() {
double radius{};
cout << "Enter the radius of the circle: ";
cin >> radius;
cout << "The area of the circle with radius " << radius << " is " << calc_area_circle(radius) << endl;
};
return 0;
}
Note: these programs will do nothing because the defined functions are not called.

How can I justify my cursor to line up with my output colums in a terminal program?

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const double PI = 3.14159;
double rad = 0;
double area = 0;
double vol = 0;
int areaPi = 0;
int volPi = 0;
cout << setprecision(5) << fixed;
cout << setw(38) << left << "Enter radius for the sphere: " << right);
cin >> rad;
area = (4 * PI * (rad * rad));
vol = ((4.0/3.0) * PI * (rad * rad * rad));
areaPi = (4 * (rad *rad));
volPi = (4 * (rad * rad * rad));
cout << right << "Surface area of the sphere: " << setw(12) << area << " (" << areaPi << "\u03C0)";
cout << "\n";
cout << "The volume of the sphere: " << setw(14) << vol << " (" << volPi << "π/3)";
cout << "\n";
return 0;
}
Hi guys. So the problem I'm having is that when you enter a value for the radius (rad) variable the cursor wants to work its way from the left to the right when the user types resulting in double digit numbers being longer than the output columns.
It looks like this when the program runs and you enter anything longer than one digit:
//Enter radius for the sphere: 17
//Surface area of the sphere: 3631.67804 (1156π)
//The volume of the sphere: 20579.50889 (19652π/3)
I would like the 7 to line up with the column below it. I tried setting the width to one less than I had before & single digits end up one space too far to the left like so:
//Enter radius for the sphere: 4
//Surface area of the sphere: 201.06176 (64π)
//The volume of the sphere: 268.08235 (256π/3)
I would store the output into a set of strings. Then you could check and manipulate the data as needed. Alternatively you could calculate the offset of spaces you'd need before printing
// convert to string for digit count
std::string output_1 = std::to_string(x);
std::string output_2 = std::to_string(y);
int o_1_2_dist = output_1.size() - output_2.size(); // difference in digits
std::string padding_1, padding_2;
if (o_1_2_dist < 0)
padding_1 = std::string(abs(o_1_2_dist), ' ');
else
padding_2 = std::string(o_1_2_dist, ' ');
std::cout << padding_1 << output_1 << '\n' << padding_2 << output_2;
you'd want to adjust on of the output strings so it doesn't count the extra bits of the number you don't care about. Maybe do output_1 = std::to_string(floor(x)); or something like that so you don't count the digits after the decimal
This can be solved by calculating the length of the input. I used c++11's to_string to convert the resulting values to strings and find out their lengths. I haven't tried how portable that is. It seems to work under linux with gcc 6.1.1., but for some reason it did not work with the input, so I changed that part as well so that the users enters a std::string which gets converted to a double afterwards.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const double PI = 3.14159;
double rad = 0;
double area = 0;
double vol = 0;
int areaPi = 0;
int volPi = 0;
int width_col1 = 40;
//cout.fill('.');
cout << setprecision(5) << fixed;
cout << left << setw(width_col1) << "Enter radius for the sphere: " << right;
std::string input;
cin >> input;
rad = stod(input);
area = (4 * PI * (rad * rad));
vol = ((4.0/3.0) * PI * (rad * rad * rad));
areaPi = (4 * (rad *rad));
volPi = (4 * (rad * rad * rad));
int indent = width_col1 + input.length() + 1;
cout << left << setw(indent - to_string(area).length()) << "Surface area of the sphere: " << area << " (" << areaPi << "\u03C0)" << std::endl;
cout << left << setw(indent - to_string(vol).length()) << "The volume of the sphere: " << vol << " (" << volPi << "π/3)" << std::endl;
return 0;
}
This solution resembles what C programmers would have done with printf.
I would love to learn why this did not work with the input.

converting to int from float

#include <iostream>
using namespace std;
int main(){
float const PI = 3.1415926;
int radius = 4;
int peri = 0;
int area = 0;
peri =(float) (PI * 2)* radius;
area = (float) PI * (radius * radius);
cout << "Radius is " << radius << endl;
cout << "Perimeter is " << peri << endl;
cout << "Area is " << area << endl;
return 0;
};
peri and area are not converting to float and always receiving a warning "converting to int from float" what seems to be the problem ..
If you really want to truncate peri and area to integers, you should do so explicitly:
peri=static_cast<int>(2*PI*radius);
area=static_cast<int>(PI*radius*radius);
Otherwise, you'll get a warning and it will look like a mistake to anyone who reads your code.

Can't get data from vector inside another vector

Let me explain the situation:
I have a class cAnimation with few methods
#include "SDL/SDL.h"
#include <vector>
#include <fstream>
using namespace std;
class cAnimation{
private:
vector<SDL_Rect> frames;
public:
cAnimation();
void setQntFrames(int n){
this->frames.resize(n);
ofstream log("qntframes.txt");
log << "capacity = " << this->frames.capacity();
}
void setFrame(int index,int x, int y, int w, int h){
this->frames[index].x = x;
this->frames[index].y = y;
this->frames[index].w = w;
this->frames[index].h = h;
ofstream log("setrect.txt");
log << "i = " << i
<< "x = " << this->frames.at(i).x
<< "y = " << this->frames.at(i).y
<< "w = " << this->frames.at(i).w
<< "h = " << this->frames.at(i).h;
}
SDL_Rect cAnimation::getFrame(int index){
return this->frames[index];
}
};
I'm doing this at my main.cpp (the includes are all ok)
vector<cAnimation> animation;
animation.resize(1);
animation[0].setQntFrames(10); // it's printing the right value on qntframes.txt
animation[0].setFrame(0,10,10,200,200) // it's printing the right values on setrect.txt
SDL_Rect temp = animation[0].getFrame(0);// here is the problem
ofstream log("square.txt");
log << "x = " << temp.x
<< "y = " << temp.y;
when i look to the square.txt log, some weird chars like squares appears and when i try to use de data of SDL_Rect temp, the application just terminate, what i'm doing wrong here to get the values?
You're probably outputting chars. When you output these to an ostream, you'll get the ASCII character, instead of the numeric value of the ASCII character. Try this:
log << "x = " << (int) temp.x
<< "y = " << (int) temp.y;
A 'char' is frequently used as short hand for a 1-byte integer. They work well for this, except that when you output them to a stream, it attempts to output them as an ASCII character, instead of as a one-byte integer. Casting the character to a true integer usually fixes the problem.