0

I have the following code where I'm asking the user to input a string 'towers' followed by integers. When I try to scanf the data inputs give the following: enter image description here

This is the code:

#include <stdio.h>   
#include <stdlib.h>   
#include <string.h>

int main(int argc, char **argv)

{
int n, from, dest;
char code[]= "towers";


printf ("Code?");
scanf ("%c ", &code);

printf ("Code?");
scanf ("%d %d %d", &n, &from, &dest);


if (strcmp(code,"towers")==0 && n==0){
n=3;
from = 1;
dest = 2;
    if (argc > 1){ 
        n = atoi(argv[1]);
    }
    towers(n, from, dest);
    exit(0);
}
else{
printf ("nothing\n");
printf ("%d",n);
}
}

What I'm trying to achieve is check user input if they type 'towers' just by itself or if they type 'towers' followed by a set of three other integers. thanks a lot for the help!

5
  • 3
    c-faq.com/stdio/scanfprobs.html Commented Feb 9, 2016 at 22:18
  • 3
    Compile with -Wall. Let the compiler show you the error of your ways. Commented Feb 9, 2016 at 22:19
  • 4
    scanf ("%c ", &code); --> scanf ("%6s", code); Commented Feb 9, 2016 at 22:20
  • Why is it that after the first scanf ("%c", &code) is executed the second scanf is completely skipped and the code continues to the if-statement? Commented Feb 9, 2016 at 22:32
  • That is because c is the format specifier for character input. Use '%6s' for your input as suggested.Then the second scanf wont be skipped. Commented Feb 9, 2016 at 23:01

1 Answer 1

4
char line[80];
int a, b, c;
fgets(line, 80, stdin);

if (sscanf(line, "towers %d%d%d", &a, &b, &c) == 3)
    /* read in towers and three ints */
else if (strcmp(line, "towers") == 0)
    /* read in towers */
Sign up to request clarification or add additional context in comments.

1 Comment

i tried it your way but its not recognizing when the user inputs "towers" without the integers. So the else if part of the statement does not run.

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.