0

I have a problem reading users input correctly.

User types "A Smaug 23 fire 10" and I need to get the all the information to my code except the first letter 'A'.

char buffer[80];
char *ret = fgets(buffer, 80, stdin)
if (ret == NULL){
     break;
}
char name[10],weapon[10];
int attackpoints, hitpoints;
int x = sscanf(ret," %s %d %s %d", name, &attackpoints,weapon,&hitpoints);

This won't work.

How can I skip the A and store users input to the right variables like name = Smaug, attackpoints = 23, weapon = fire, etc?

1
  • Like this int x = sscanf(ret," %*s %s %d %s %d", name, &attackpoints, weapon, &hitpoints); where the first specifier with a * reads but ignores (several) chars. Commented Apr 8, 2020 at 13:45

1 Answer 1

1

You just need to add the string A[2] for the first letter. Read all string and print all of value expect A:

char A[2], name[10],weapon[10];
int x = sscanf(ret,"%s %s %d %s %d", A, name, &attackpoints,weapon,&hitpoints);

The complete code:

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

int main(int argc, char *argv[]) {
    char buffer[80];
    char *ret = fgets(buffer, 80, stdin);
    if (ret == NULL)
         exit(-1);
    char A[2], name[10],weapon[10];
    int attackpoints, hitpoints;
    int x = sscanf(ret,"%s %s %d %s %d", A, name, &attackpoints,weapon,&hitpoints);
    if (x != 5)
        exit(-1);
    printf("name = %s, attackpoints = %d, weapon = %s, hitpoints = %d\n", name, attackpoints, weapon, hitpoints);
    return 0;
}

The input and ouput:

./test 
A Smaug 23 fire 10
name = Smaug, attackpoints = 23, weapon = fire, hitpoints = 10
Sign up to request clarification or add additional context in comments.

2 Comments

Okay, I thought it could be done some other way but that is good also.
@konde020202: It could be done another way, e.g. by having a literal "A " at the start of your scanf format string that the input has to match before scanf will move on to later conversions. See the docs, e.g. en.cppreference.com/w/c/io/fscanf which mention literal non-whitespace characters.

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.