0

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.

UPDATE: I found a different solution for my project. The solution is specific to my code, and it won't work in other circumstances, so it's pointless to upload it. Thank you for your time.

xDev120
  • 67
  • 8
  • `cin >> response;` like you already did it with the `double`, but that will read the `` left by the `cin >> num1;`, so you have to add a `cin.ignore();` in between: https://godbolt.org/z/9Yo5bxx6a – mch Dec 28 '21 at 12:07
  • Please don't accept bad answers. – JHBonarius Dec 28 '21 at 12:47
  • You're only limiting the number of characters that you will read, NOT the number of characters that can be entered. If you tried testing it by typing more than one character, your C-string is malformed due to missing a null character. – sweenish Dec 28 '21 at 12:53

1 Answers1

-2

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[3] { }; // resonse should be able to take in 3 chars (2 + 1 for '\0')

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

Then you can use std::strtold to convert any string buffer (char*) to a long double.

digito_evo
  • 3,216
  • 2
  • 14
  • 42