3

How can I use scanf to read either an int or a string?

What I'm trying to do is:

printf("Enter Your Guess, 0 - 100: "); /* Input your guess */

scanf("%as", &pass);

printf("%s", pass);

In this program the player can either chose to enter a number or pass how can I scan either the number or the word pass. Is there and if statement I can put in or something I've been going into this for like 1 hour

1
  • 4
    Use a fgets followed by combination of strcmp and strtoul. Commented Apr 3, 2013 at 21:53

2 Answers 2

2

scan in a string, and determine whether it is made entirely of legal symbols for a number or whether the string says "pass", and if it is a number, than you can convert it to the type of your choice.

Sign up to request clarification or add additional context in comments.

Comments

0

Well, a workaround would be to simply read a string all the time and use atoi or snprintf to convert the desired string to a number if it contains no other characters except [0-9]

1 Comment

Using snprintf() won't convert a string to an integer; presumably, you meant sscanf(). Using strtol() or strtod() or one of their relatives would probably be a good choice — though they are subtle functions which require care to be used properly.

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.