0

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;
}
Andrew T
  • 186
  • 2
  • 11

2 Answers2

1

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

Xiaotian Pei
  • 3,210
  • 21
  • 40
1

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);
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Haris
  • 12,120
  • 6
  • 43
  • 70