Question

I want the program to answer the first and last name separately while also accepting the input strictly to alphabets. Where do I find more info about that?? Thanks.

#include <stdio.h>

int main(void)
{
      char MyFname[20];
      char MyLname[20];
      printf("Enter your first and last names: \n");
      scanf(" %s %s", MyFname, MyLname);
      printf("Goodbye %s %s, have a great day!", MyFname, MyLname);
      return 0;
}
Was it helpful?

Solution

Edited to incorporate @chux's suggestions.

You can use character-classes in the conversion specification string.

#include <stdio.h>
int main() {
    char alphabetic_string[80], numeric_string[80];

    scanf(" %79[a-zA-Z] %79[0-9]", alphabetic_string, numeric_string);

    return 0;
}

To ask two separate questions, uh, ask two separate questions!

#include <stdio.h>
int main() {
    char ans1[80], ans2[80];

    printf("Input answer to question 1: ");
    fflush(NULL);
    scanf(" %79[a-zA-Z]", ans1);
    printf("Input answer to question 2: ");
    fflush(NULL);
    scanf(" %79[a-zA-Z]", ans2);

    return 0;
}

OTHER TIPS

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

int main()
{
  char buff[1024];
  char MyFname[20];
  char MyLname[20];

  if ( fgets ( buff, sizeof buff, stdin ) != NULL )
  {
    if ( sscanf ( buff, "%[a-zA-Z] %[a-zA-Z]", MyFname, MyLname ) != 2 ) 
    {
      fprintf ( stderr, "Invalid input\n" );
      exit ( EXIT_FAILURE );
    }
  }

  printf ( "Goodbye %s have a great day!\nGoodbye %s have a great day!", MyFname, 
  MyLname );

  return 0;

}

Enter your first and last names:

John smith

Goodbye John have a great day!

Goodbye smith have a great day!

It is best to use fgets to take input and then verifying with sscanf. sscanf will successfully return the total number of inputs read if format entered is correct.

Don't forget to leave space when entering first and last name i.e John smith

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top