Andrew T
Andrew T

Reputation: 186

Trying to take someone's full name and return their initials in C

I am new to C and I am trying to write a program that takes an entered name, like john smith, and returns the uppercase initials, JS. I've tried using a for loop and a while loop, but my code does not seem to increment, whenever I run it all it returns is the first initial. I've searched the web for this problem, but none of the solutions worked for me. What am I doing wrong? Thanks in advance.

Here is the code:

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

int main(void) {
  // initialize variables
  char name[61];
  int i = 0;

  // ask for user input
  printf("Please enter your name: ");
  scanf("%s", name);

  // print first initial
  printf("%c", toupper(name[0]));

  // print the next ones
  while (name[i] != '\0') {
    if (name[i] == ' ') {
      i++;
      printf("%c", toupper(name[i+1]));
    }
    i++; // does not increment
  }
  return 0;
}

Upvotes: 0

Views: 846

Answers (2)

Haris
Haris

Reputation: 12272

scanf() reads the input until a space is encountered. So writing the full name will have a space in between the first and the last name. That would stop scanf() and it would read only the first name.

To read both input with space, better use fgets(). fgets() reads the string until a newline \n is encountered.

fgets(name, 61, stdin);

Upvotes: 1

Xiaotian Pei
Xiaotian Pei

Reputation: 3260

scanf("%s", name) only reads the first name. You need something like scanf("%s %s", first_name, last_name)

Upvotes: 1

Related Questions