Home > Enterprise >  C store cin.getline value to double variable and to char variable
C store cin.getline value to double variable and to char variable

Time:12-29

In my program, I want to limit the amount of numbers a user can input using cin.getline(variable, N) . My code looks like this (this is not the whole code):

#include <iostream>

int main()
{   
    input:
    long double num1;
    long double num2;
    long double result;
    char response;
    cout << "Enter first number and then press enter" << endl;
    cin >> num1;
    cout << "Enter   to add, - to substract, * to multiply, / to divide, v to find the sqare root and ^ to find the power" << endl;
    cin.getline(response, 2); //Here is the problem!
}

When I run this, I get the following error:

Error message screenshot

How can I store the value returned by cin into a double and a char variable?

Please let me know if you want extra information.

CodePudding user response:

You can't get a number using cin.getline. Instead get a buffer of chars and then convert it to double.

#include <iostream>    
int main()
{   
    input:
    long double num1;
    long double num2;
    long double result;
    char response[10] { }; // char buffer
    cout << "Enter first number and then press enter" << endl;
    cin >> num1;
    cout << "Enter   to add, - to substract, * to multiply, / to divide, v to find the sqare "
    "root and ^ to find the power" << endl;
    cin.getline(response, 2); // fill the buffer
    result = std::stold( std::string(response) ); // convert the buffer to long double
}
  • Related