2

I'm told that I should, unless beyond necessary, only use either of the two in my code, cin or getline.

Cin I am told creates unusual errors and such (Not checking type of input, etc )

I understand getline() is much more flexible with strings and characters, but how about numeric types? I mean, I can parse a getline string to a numeric value, but isn't there a safer route? Question being, which method should I take for both string AND numerical input?

int inputReturn(int x);

int defaultValue = 0;

int main()
{

  //Getting numerical input w/getline()
  string input = "";

  while(true)
   {
    cout << "Enter a value: ";
    getline(cin, input);

    stringstream myStream(input);
    system("CLS");

    if(myStream >> defaultValue)
      {
        system("CLS");
        break;
      }
    cout << "Invalid input. Try again!" << endl << endl;

   }

    inputReturn(input); //Converted to numeric value, but still type of string (Error)
    system("CLS");

return 0;
}

int inputReturn(int x)
{
  return x*2;
}

In this example, I parse string input to a numeric value then use the value as a parameter of int and get an error of string to int.

So, question - what should I use for these data types or can I use both?

I hope you guys understand my questioning.

  • 1
    You can use a `std::istringstream ` to convert from a `string ` to numeric values. – πάντα ῥεῖ Oct 15 '15 at 09:56
  • 1
    The error will be fixed by writing `inputReturn(defaultValue);` BTW. – πάντα ῥεῖ Oct 15 '15 at 10:00
  • 1
    you can use both.. though the `>>` operator reads your the values up-to next space or EndOfLine or eof or the sizeof/capacity of the target . and yes types are not checked when using `cin` with `>>` and getline.. the difference with getline is that it always returns a string. – Minato Oct 15 '15 at 10:12
  • 1
    if you are guaranteed your input is well formed (numbers are where you expect them) than `cin` will not have a problem. but based on your wording of the question, that doesn't sound like the case. So, you must read strings, or use a better parser. +1 for `inputReturn()` – Les Oct 15 '15 at 10:20
  • Mubashir Hanif and Les, thank you for the comments (That were more like answers). Solved my question fully. – Enthused Binary Oct 15 '15 at 10:25
  • There's another problem with mixing the two -- see [c++ - Why does std::getline() skip input after a formatted extraction? - Stack Overflow](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – user202729 Jan 31 '21 at 03:20

1 Answers1

0

getline() is okay to use for numerical values but it cannot be used for ints or doubles. In your case, it is okay to use.

also remember to #include <string>

  • also, with that error in the conversion, you should use casting, it works much better with this type of conversion – FrostByte May 15 '20 at 00:29