1

In C++,

#include <iostream>
using namespace std;

int main ()
{
    int i;
    cin >> i;
    cout << i;
    return 0;
}

If we input a string to i, for example, "integer", it will display 0 when cout, which means that the string becomes 0. Could it be possible to make the string become some other integer, 10000 for example?

Hans Chen
  • 13
  • 1
  • 3
  • What have you tried? Setting a number to 10,000 is something you should really try to do yourself before running to us for help. – The Forest And The Trees Jan 28 '15 at 08:43
  • Take a look at this: http://stackoverflow.com/questions/10314682/user-inputcin-default-value Maybe it will help you out – eren Jan 28 '15 at 08:47
  • 1
    You could build your own class `Foo`, and a global operator function for `>>` for your class and a stream. You could even build syntax to support `cin >> setFooDefault(1) >>`. Your class could even have a cast operator to `int`. That said, @PaulR's answer is more sensible. – Bathsheba Jan 28 '15 at 08:47

2 Answers2

3

Sure - you can just do something like this:

#include <iostream>
using namespace std;

int main ()
{
    int i = 10000;   // initialise i to default value
    int temp;        // temporary integer for input validation

    if (cin >> temp) // if valid integer entered
        i = temp;    // set i to entered integer (otherwise leave it at default value)
    cout << i << endl;
    return 0;
}

Compile and test:

$ g++ -Wall input.cpp 
$ ./a.out
1234
1234
$ ./a.out
fred
10000
$ 
Paul R
  • 208,748
  • 37
  • 389
  • 560
-1

You'd have to input it to a string variable then examine the string and work out what to do

Tom Tanner
  • 9,244
  • 3
  • 33
  • 61