0

while entering a name e.g: Alpha Beta, i cannot seem to get scanf to read the word after the blank space("Beta")...

#include<stdio.h>

struct student
{
 int rollno, class; 
 char name[50], div[10];
};

int main()
{
struct student s1, *ptr;
ptr = &s1;
printf("\nEnter Student Class: ");
scanf("%d",&ptr->class);
printf("\nEnter Student Division: ");
scanf("%s",&ptr->div);
printf("\nEnter Student Rollno: ");
scanf("%d",&ptr->rollno);
printf("\nEnter Student Name: ");
scanf("%49s",&ptr->name);

printf("\nClass: %d\n", ptr->class);
printf("\nDivision: %s\n", ptr->div);
printf("\nRollno: %d\n", ptr->rollno);
printf("\nName: %s\n", ptr->name);
return 0;
}

when printing name, it returns only 'Alpha', not 'Alpha Beta' what should i do to get it to read both Alpha and Beta?

  • Does this answer your question? [What does space in scanf mean?](https://stackoverflow.com/questions/6582322/what-does-space-in-scanf-mean) – dustin2022 Jun 17 '20 at 06:54
  • From man scanf: "`%s` Matches a sequence of **non-white-space** characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first. " – Mathieu Jun 17 '20 at 07:19
  • Worth reading: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html – Mathieu Jun 17 '20 at 07:20

2 Answers2

1

Scanf() only scans non white spaces. For getting whitespaces as well you could use fgets(). Example-

fgets(&ptr->name, 20, stdin)

20 is arbitrary. Choose how many characters you need. Docs for reference- https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fgets-fgetws?view=vs-2019

Rattandeep
  • 75
  • 1
  • 2
  • 8
0

Try this:

#include<stdio.h>

struct student
{
 int rollno, class; 
 char name[50], div[10];
};

int main()
{
struct student s1, *ptr;
ptr = &s1;

printf("\nEnter Student Class: ");
scanf("%d",&ptr->class);
printf("\nEnter Student Division: ");
scanf("%s",ptr->div);
printf("\nEnter Student Rollno: ");
scanf("%d",&ptr->rollno);
printf("\nEnter Student Name: ");
scanf(" %50[A-Za-z ]",ptr->name);

printf("\nClass: %d\n", ptr->class);
printf("\nDivision: %s\n", ptr->div);
printf("\nRollno: %d\n", ptr->rollno);
printf("\nName: %s\n", ptr->name);

return 0;
}

Execution:

./student

Enter Student Class: 1

Enter Student Division: 2

Enter Student Rollno: 3

Enter Student Name: Alpha Beta

Class: 1

Division: 2

Rollno: 3

Name: Alpha Beta
pifor
  • 7,419
  • 2
  • 8
  • 16