Starchaser Starchaser - 2 months ago 20
C Question

How to check if a string is empty in C (nothing has worked so far)

I have to make a code that checks to see whether the Student 1's first name was blank and if it was then ask the user to input a name. However, when I use this code it doesn't display that message. When I press enter the cursor just goes to the next line until I actually type something in. I've tried this with strcmp too and nothing works.

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

char charStudent1FirstName[50] = "";

printf("Please enter Student 1's First name: ");
scanf("%s", &charStudent1FirstName);

if (charStudent1FirstName[0] == '\0')
{
printf("Please input Student 1's first name again: ");
scanf("%s", &charStudent1FirstName);
}
}

Answer

Here's what I changed:

  1. Use fgets instead of scanf. This means you will actually see the blank line if that's all that's entered.
  2. Trim the newline from the fgets result.
  3. Use charStudent1FirstName instead of &charStudent1FirstName. You want to pass a char*, not a char**. If your compiler doesn't warn you about this, consider using a different compiler or changing your compilation settings.
  4. Use a loop so the user is prompted to enter a name as many times as necessary until one is entered.

Complete working code:

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

int main() {

    char charStudent1FirstName[50] = "";

    while (charStudent1FirstName[0] == 0) {
        printf("Please input Student 1's first name: ");
        fgets(charStudent1FirstName, 50, stdin);
        charStudent1FirstName[strcspn(charStudent1FirstName, "\n")] = 0;
    }

    printf("First name: %s\n", charStudent1FirstName);
}
Comments