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?

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. Commented Jan 28, 2015 at 8:43
  • Take a look at this: stackoverflow.com/questions/10314682/… Maybe it will help you out Commented Jan 28, 2015 at 8: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. Commented Jan 28, 2015 at 8:47

2 Answers 2

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
$ 
Sign up to request clarification or add additional context in comments.

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.