Question

I'm doing a C++ assignment that requires taking user input of an expression (eg: 2 * (6-1) + 2 ) and outputting the result. Everything works correctly unless a space is encountered in the user input.

It is a requirement to pass the user input to the following method;

double Calculate(char* expr);

I'm aware the issue is caused by c_str() where the space characters act as a terminating null byte, though I'm not sure how to overcome this problem.

Ideally I'd like to preserve the space characters but I'd settle for simply removing them, as a space serves no purpose in the expression. I get the same result when using string::data instead of c_str.

int main(int argc, char **argv)
{
    string inputExpr;
    Calc myCalc;

    while(true) {
        cin >> inputExpr;
        if(inputExpr == "q") break;

        cout << "You wrote:" << (char*)inputExpr.c_str() << endl; // debug
        printf("Result: %.3f \n\n", myCalc.Calculate( (char*)temp.c_str() ) );
    }
    return 0;
}
Was it helpful?

Solution

c_str works just fine. Your problem is cin >> inputExpr. The >> operator only reads until the next space, so you do not read your equation fully.

What you want to use is std::getline:

std::getline (std::cin,inputExpression);

which will read until it reaches a newline character. See the function description if you need a specific delimiter.

OTHER TIPS

Problem is not with inputExpr.c_str() and c_str as such, c_str() returns pointer to a character array that contains a null-terminated sequence. While reading through cin, you get space or tab etc separating as multiple strings. Check with the content of the string that way to solve the intended operation

First, I think your Calculate() method should take as input a const char* string, since expr should be an input (read-only) parameter:

double Calculate(const char* expr);

Note that if you use const char*, you can simply call std::string::c_str() without any ugly cast to remove const-ness.

And, since this is C++ and not C, using std::string would be nice:

double Calculate(const std::string& expr);

On the particular issue of reading also whitespaces, this is not a problem of terminating NUL byte: a space is not a NUL.
You should just change the way you read the string, using std::getline() instead of simple std::cin >> overload:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string line;
    getline(cin, line);
    cout << "'" << line << "'" << endl;
}

If you compile and run this code, and enter something like Hello World, you get the whole string as output (including the space separating the two words).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top