laura
laura

Reputation: 2135

Detect a new line character

I am reading from stdin students in a structure array. After the details are introduced for one student, i ask for another student details. if the choice is Y, i'll add the new student, if the choice is N, break. But what if the choice is simply ENTER? How can i detect the new line character? I tried with getchar(), but it skips the first reading from stdin.When i debug it doesn't stops to the first line test=getchar(), it stops to the second one.

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

struct student
{
char name[20];
int age;
};

int main()
{
struct student NewStud[5];
char test;
int count=0;
for(count=0;count<5;count++)
{
    printf("Enter the details for %s student: ",count>0?"another":"a");
    printf("\nName : ");
    scanf("%s",NewStud[count].name);
    printf("\nAge : ");
    scanf("%d",&NewStud[count].age);
    printf("Would you like to continue? (Y/N)");
    test=getchar();
    if(test=='\n')
    {
        printf("Invalid input. Would you like to continue? (Y/N)");
        test=getchar();
    }
    while(tolower(test) !='n' && tolower(test) != 'y')
    {
        printf("Invalid input.Would you like to continue? (Y/N)");
        test=getchar();
    }
    if(tolower(test) == 'n')
    {
        break;
    }
    if(tolower(test) == 'y')
    {
        continue;
    }
}


getch();
}

Upvotes: 2

Views: 10354

Answers (4)

Compare test value with '\n', like this sample:

int main() {
    int test;
    test = getchar();
    printf("[%d]\n", test);
    if(test == '\n') printf("Enter pressed.\n");
    return(0);
}

ps: your test must be int.

Upvotes: 0

majordd
majordd

Reputation: 1

You could replace

> test=getchar();
>     if(test=='\n')
>     {
>         printf("Invalid input. Would you like to continue? (Y/N)");
>         test=getchar();
>     }

with

while((test=getchar()) == '\n')
{
  printf("Invalid input. Would you like to continue? (Y/N)");
}

Upvotes: 0

Mike
Mike

Reputation: 49373

The problem is that scanf() leaves a newline character in the input stream, you have to consume it before you'll get "valid" data in getchar().

Ex:

scanf("\n%s",NewStud[count].name);
getchar();
printf("\nAge : ");     
scanf("%d",&NewStud[count].age);
getchar();
printf("Would you like to continue? (Y/N)");
test=getchar();   // Now this will work

Check out this link for more info. It's for fgets, but it's the same problem with getchar()

Upvotes: 2

Yarneo
Yarneo

Reputation: 3000

Of course it skips the first reading, you put it in an if statement like so: if(test=='\n')

You got all the info for that certain student and then the user pressed enter, so you go back up to for(count=0;count<5;count++) and ask for new input for a new student. I think what you wanted to do is use a while statement instead.

Upvotes: 0

Related Questions