Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string input with spaces [duplicate]

Tags:

c

string

gcc

ubuntu

I'm trying to run the following code in the basic ubuntu gcc compiler for a basic C class.

#include<stdio.h>

struct emp
{

  int emp_num, basic;
  char name[20], department[20];

};

struct emp read()
{
  struct emp dat;

  printf("\n Enter Name : \n");
  scanf("%s", dat.name);

  printf("Enter Employee no.");
  scanf("%d", &dat.emp_num);

  //printf("Enter department:");
  //fgets(dat->department,20,stdin);

  printf("Enter basic :");
  scanf("%d", &dat.basic);

  return dat;
}

void print(struct emp dat)
{
  printf("\n Name : %s", dat.name);

  printf("\nEmployee no. : %d", dat.emp_num);

  //printf("Department: %s", dat.department);

  printf("\nBasic : %d\n", dat.basic);
}

int main()
{
  struct emp list[10];

  for (int i = 0; i < 3; i++)
  {
    printf("Enter Employee data\n %d :\n", i + 1);
    list[i] = read();
  }

  printf("\n The data entered is as:\n");

  for (int i = 0; i < 3; i++)
  {
    print(list[i]);
  }

  return 0;
}

I want the name to accept spaces.

The problem comes when I'm entering the values to the structures. I am able to enter the name the first time but the subsequent iterations don't even prompt me for an input.

I've tried using fgets, scanf("%[^\n]",dat.name) and even gets() (I was desperate) but am the facing the same problem every time.

The output for the 1st struct is fine but for the rest is either garbage, the person's last name or just blank.

Any ideas?

like image 848
Suman Roy Avatar asked Aug 25 '26 23:08

Suman Roy


1 Answers

When reading a string using scanf("%s"), you're reading up to the first white space character. This way, your strings cannot include spaces. You can use fgetsinstead, which reads up to the first newline character.

Also, for flushing the input buffer, you may want to use e.g. scanf("%d\n") instead of just scanf("%d"). Otherwise, a subsequent fgets will take the newline character and not ask you for input.

I suggest that you experiment with a tiny program that reads first one integer number and then a string. You'll see what I mean and it will be much easier to debug. If you have trouble with that, I suggest that you post a new question.

like image 97
nickie Avatar answered Aug 27 '26 17:08

nickie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!