Возврат потока строки (char *) - PullRequest
0 голосов
/ 07 февраля 2012

Мой преподаватель хочет, чтобы я вывел "площадь" из CalculateArea как символ / строка. Я не уверен, что именно он имеет в виду, но, возможно, некоторые из вас могут понять.

#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;
}

Я получаю вывод как это:

Какой у тебя диаметр? 12

Какой у тебя аккорд? 10

Угол: 33,5573

X: 3,31662 дюйма

ч: 2,68338 дюйма

Отладка: область: 18,8553 дюйма

Отладка: площадь: 18,8553 дюйма

T

Мне нужно выяснить, как вернуть строку, на которую указывает tStr. Если вы не понимаете, о чем я говорю, извините, я не совсем уверен, о чем просит профессор.

1 Ответ

1 голос
/ 07 февраля 2012

Вы получаете ссылку на символ, а не строку. (* tStr говорит «дай мне содержимое указателя»)

Более правильная версия того, что вы пытаетесь:

const char* calculateArea(double diameter, double chord)

и

return tStr; // no 'content of'

Но это все равно плохо: возвращаемая строка «выходит за рамки», когда aStr выходит из области видимости, поэтому вам действительно нужно вернуть копию символов или просто вернуть саму строку (и позволить std lib беспокоиться о копия для вас)

const string calculateArea(double diameter, double chord)

...

return aStr;
...