user3822731
user3822731

Reputation: 3

C programming getchar()

I have two problems writing my code. The first problem I have is getting my getchar() to work if the user enters no text and just hits enter. I need to print an error if they do so and prompt the user to reenter the text in a loop until they do enter text. Is there any way to do so because everything I have tried has failed. Here is the code I have for that section:

printf("Enter a text message: ");
while((c=getchar()) != '\n' && c != EOF)
{
        text[i]= c;
        i++;
}

I am new to C so I am limited on ideas to fix my dilemma. As you can see I am setting the input equal to an array. This leads to my second problem, I need to limit the input to no more than 100 characters. But, instead of giving the user an error I need to just chop off the extra characters and just read the first 100.

Upvotes: 0

Views: 1764

Answers (3)

Yedhu Krishnan
Yedhu Krishnan

Reputation: 1245

The simplest solution to your problem is to use fgets. We can give limit to the input so that it doesn't read the extra characters after the given limit.

Refer this sample code. Here I am printing the string if the user is not pressing Enter key:

#include <stdio.h>

int main() 
{
    char str[100];
    fgets(str, 100, stdin);
    if(str[0] != '\n')
    {
        puts(str);
    }
    return 0;
}

Upvotes: 1

ooga
ooga

Reputation: 15501

#include <stdio.h>

#define MAXSIZE 100

int main() {
  char text[MAXSIZE+1]; // one extra for terminating null character
  int i = 0;
  int c;

  while (1) {
    printf("Enter a text message: ");

    i = 0;
    while ((c = getchar()) != '\n' && c != '\r' && c != EOF) {
      if (i < MAXSIZE) {
        text[i]= c;
        i++;
      }
    }
    if (i > 0 || c == EOF)
      break;
    printf("Empty string not allowed.\n");
  }

  text[i] = '\0';

  printf("You entered: %s\n", text);

  return 0;
}

Test code to detect non-compliant system:

#include <stdio.h>

int main() {
  int c;
  printf("Just hit enter: ");
  c = getchar();
  if (c == '\r')
    printf("\\r detected!!!\n");
  else if (c == '\n')
    printf("\\n detected.\n");
  else
    printf("Yikes!!!\n");
  return 0;
}

Upvotes: 1

Abhishek Mittal
Abhishek Mittal

Reputation: 366

First of all getchar() can take only one character an input. It cannot take more than one character.

char c;
int total_characters_entered = 0;
do
{
    printf ("Enter a text message: ");
    c = getchar();

    if (c != '\n')
    {
        total_characters_entered++;
    }

} while (total_characters_entered <= 100);

I have written some code that will iterate in while loop until user has entered 100 characters excluding "Simple Enter without any text"

Please let me know if it does not satisfy your requirement. We will work on that.

Upvotes: 0

Related Questions