返回字符串流(char *)

时间:2012-02-07 00:41:40

标签: c++ char ostringstream

我的教授希望我从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英寸

     

h:2.68338英寸

     

调试:面积为:18.8553英寸

     

调试:面积为:18.8553英寸

     

Ť

我需要弄清楚如何返回字符串tStr指向。如果你不明白我说的话,抱歉,不确定教授的要求是什么。

1 个答案:

答案 0 :(得分:1)

您正在查找char引用而不是字符串。 (* 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;