invalid character are printed in program - c

I have written the program
#include<stdio.h>
struct student
{
char name[22];
char rollno[10];
unsigned long long int phno;
};
int main()
{
int i,j;
char c[1];
struct student cse[10],*p;
p=cse;
for(i=0;i<3;i++)
{
printf("enter student name\n");
gets(cse[i].name);
printf("enter student roll number \n");
gets(cse[i].rollno);
printf("enter student phone number \n");
scanf("%llu",&cse[i].phno);
gets(c); //to catch the '\n' left unprocessed by scanf
}
for(i=0;i<3;i++);
printf("the following is the information about CSE B student\n");
printf("%-6s%-24s%-14s%-14s \n","S.no","student Name","Roll no","phone no.");
for(i=0;i<3;i++)
{
printf("%-6d%-24s%-20s%-14llu \n",i+1,(*p).name,(*p).rollno,(*p).phno);
++p;
}
return 0;
}
the output is
the following is the information about CSE B student
S.no student Name Roll no phone no.
1 kapil 1234567890��I 1234567890
2 kumar 9876543210��L 9876543210
3 sharma 5123467890��a1 5123467980
there are some unwanted and ununderstandable characters in the Roll no coloumns ,what is the cause of printing of those invalid characters
~

The array rollno has storage only for 10 chars but you are inputting 10 or more chars. If your roll numbers are 10 digits, you need at least 11 chars to print it as string, one extra for the terminating null-byte. This is technically undefined behaviour, making your program invalid.
Note that gets() has been deprecated since C11 and you should really be using fgets() instead.

Related

Correct output when there are upto 9 digits but wrong when there are 10 digits of mob number variable

Output shows correct when the phone number variable is upto 9 digits only but shows some random value for 10 digits. Why is this happening?
Please help.
#include<stdio.h>
typedef struct hotel
{
char c_name[20];
int no_days;
struct phone_number
{
int mob;
int alt_mob;
}ph;
}h;
void read(h*);
void display(h s);
int main()
{
h h1;
read(&h1);
display(h1);
}
void read(h* s)
{
printf("Enter your name: ");
scanf("%s",&(s->c_name));
printf("Enter the number of days: ");
scanf("%d",&(s->no_days));
printf("Enter the phone number: ");
scanf("%d",&((s->ph).mob));
printf("Enter the alternate number: ");
scanf("%d",&((s->ph).alt_mob));
}
void display(h s)
{
printf("%s %d %d %d",s.c_name,s.no_days,s.ph.mob,s.ph.alt_mob);
}
On most systems, an int is 32 bit, which means it has a maximum value of 2147483647. So any value larger than this will overflow.
Phone numbers aren't really "numbers", so they shouldn't be stored in a numerical data type. You're better off storing it as a string.

Unexpected output of scansets in C

as expected this prog. should accept a number until it encounters a 4 but it gives some garbage value. why?
int main(void)
{
int a;
printf("Enter a number: ");
scanf("%[^4]d", &a);
printf("You entered: %d\n", a);
return 0;
}
As far as I know scansets are meant to be used with strings (which makes the d not act as an integer placeholder specification). One way to write it is to read the input into a string and then parse it:
int main(void)
{
int a;
char b[255];
printf("Enter a number: ");
scanf("%254[^4]", &b);
a = atoi(b);
printf("You entered: %d\n", a);
return 0;
}
I'm keeping the modified code to a minimum, you'd definitely need some extra checks for input sanity.
To clarify: The 254 prefix limits the amount of data that scanf will capture, so as to not exceed the size of the buffer (strings are terminated with an extra null character, so the read length must be smaller than the actual size)1.
The scanset working with only characters.
Here is my sample code. (but, I don't know what you really want.)
#include <stdio.h>
int main(void) {
char buffer[128];
printf("Enter a number: ");
scanf("%[^4]s", buffer);
printf("You entered: %s\n", buffer);
return 0;
}
The result is,
Enter a number: 12345678
You entered: 123
Additionally, if you want integer value, use atoi().

how to display entered letter in c?

I am new to c programming. I have created a program for entered letters and finally displayed the entered letters.. but it displayed only final letters always.. please help .. i know its simple question but am beginner so please help guys..
#include<stdio.h>
int main()
{
char z;
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%s\n",&z);
}
return 0;
}
Problems:
You should use %c (for character) instead of %s (for string).
Use a character array for storing multiple characters. Read about arrays here.
Remove & from printf() in the second for loop.
Try this:
int main()
{
char z[10]; //can hold 10 characters like z[0],z[1],z[2],..
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",&z[i]);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]);
}
return 0;
}
Please look into this for more details on scanf. You have given scanf("%s",&z); %s is for reading strings(array of chars except newline char and ended with null char). So if you put this inside loop you wont get desired result. And if you want read only a char at a time use %c here c for Character.
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",z+i);
}
char z is a place holder for one character only. And you are over writing what you set z to in the for loop. To take in more characters, use a char array as others have mentioned.
Or print the characters in the same you loop you are scanning them:
#include<stdio.h>
int main()
{
char z;
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z);
printf("letter scanned:%c\n", z);
}
return 0;
}
Letters are scanned using %c. And to scan multiple letters you can use char array: char z[10];
What you are trying to do can be done this way:
char z[10]; // Take some max size array
...
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",&z[i]); // Scan the letters on each array position.
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]); //'printf' doesn't require address of arg as argument hence no `&` required
}
%s argument is used to scan a string of chars.
Note the difference between string of chars and array of chars. The string of chars in C needs to be terminated with ASCII Character 0 represented as \0 in char format, while the array of char is just a collection of letters which need not be terminated with \0.
The difference becomes more important when you try to perform some operation on strings such as printf, strcpy, strlen, etc.. These functions work on null character termination property of string.
For Example: strlen counts the characters in the string till it finds \0, to find out the length of string. Similarly, printf prints the string character by character until it finds the \0 character.
UPDATE:
Forgot to mention that scanf is not a good option to input char format. Use fgetc instead, with stdin as input FILE stream.
#include <stdio.h>
int main()
{
char *z;
int a;
printf("enter the no.");
scanf("%d",&a);
z = (char *) malloc(a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",z+i);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z);
}
return 0;
}
first error in your code is you have used "%s" instead of "%c".Second is it is impossible to store multiple values in one variable so instead of using variable use arrays.third is that you have told the user to enter the number of character that he/she wants to entered which you don't know.They can enter 1 also and 100000 also so the number of members in array is not defined.Better is to use specific number of characters in array.
finally i got the answer thank you for the help stackoverflow guys simply rocks ...
#include<stdio.h>
#include<malloc.h>
int main()
{
int a;
char *z=(char *)malloc(sizeof(a));
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z[i]);
}
printf("the entered letters are:\n");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]);
}
return 0;
}

Structures in C Language

what is mistake ? i cant find any mistake in my code but it does not take input properly and it also displays some garbage values.
Thanks:
int main()
{
struct book
{
char name;
int price;
int pages;
};
struct book b[5];
int i;
for (i = 0; i < 5; i++)
{
printf("enter name price pages\n");
scanf("%c", &b[i].name);
scanf("%d", &b[i].price);
scanf("%d", &b[i].pages);
}
for (i = 0; i < 5; i++)
printf("%c %d %d\n", b[i].name, b[i].price, b[i].pages);
return 0;
}
Most books have a name that is longer than a single letter.
You need to adjust the structure accordingly:
enum { MAX_BOOKNAMELEN = 32 }; // Probably too short
struct book
{
char name[MAX_BOOKNAMELEN];
int price;
int pages;
};
You also need to adjust the input:
if (scanf("%31[^\n]", b[i].name) != 1)
...report error; do not use this book entry...
The '31' is magicked out of thin air; it is one less than MAX_BOOKNAMELEN. Note that book titles frequently contain spaces; thus %s which skips leading spaces and stops at the first space after one or more non-space characters is not appropriate for reading titles. One way to create the format string is via sprintf() — this will adapt if MAX_BOOKNAMELEN changes size:
char name_fmt[16];
snprintf(name_fmt, sizeof(name_fmt), "%%%d[^\n]", MAX_BOOKNAMELEN-1);
if (scanf(name_fmt, b[i].name) != 1)
...error...
A more thorough revision would probably use fgets() and sscanf() or other tools instead of calling scanf() directly.
this line
scanf("%c",&b[i].name);
should be
scanf(" %c",&b[i].name);
See How to do scanf for single char in C
Since I've been informed to specifically answer the question (sorry, Im new here), the problem lies in the %c picking up whitespace and/or newline characters. The easiest way to prevent this is put a " " in front of it.
#include <stdio.h>
int main()
{
struct book
{
char name;
int price;
int pages;
};
struct book b[5];
int i;
for(i=0;i<5;i++)
{
printf("enter name price pages\n");
scanf(" %c %d %d",&b[i].name, &b[i].price, &b[i].pages); //here
//%c was grabbing whitespace and/or newline causing the problem.
}
for(i=0;i<5;i++)
printf("Name: %c Price: %d Pages: %d\n",b[i].name,b[i].price,b[i].pages);
return 0;
}
Output:
enter name price pages
a 1 2
enter name price pages
b 3 4
enter name price pages
c 5 6
enter name price pages
d 7 8
enter name price pages
e 9 10
Name: a Price: 1 Pages: 2
Name: b Price: 3 Pages: 4
Name: c Price: 5 Pages: 6
Name: d Price: 7 Pages: 8
Name: e Price: 9 Pages: 10
What happens is that the last scanf("%d"), reads the number and let a '\n' at the buffer, so next time you call scanf("%c"), it will read the '\n' in the buffer, and not the new character.
One possible solution to use scanf, is to tell scanf to read everything in the line, and discard it:
scanf("%c%*[^\n]\n", &b[i].name);
scanf("%d%*[^\n]\n", &b[i].price);
scanf("%d%*[^\n]\n", &b[i].pages);
This way, scanf will block until you press enter, and will read the '\n'.
try it like this :
scanf(" %c %d %d",&b[i].name, &b[i].price, &b[i].pages);
while(getchar()!='\n');

C scanf() doesn't parse my input

I am writing a C program and that program objective is I want to enter only 4 students details with structures. But my program missing something so my program exiting after entering the first student details. Look at here please
# include <stdio.h>
struct student
{
int no;
char name[20];
float marks;
}s[10];
int main()
{
int i,n;
printf(" enter number of students ");
scanf("%d",&n);
printf(" enter student Number Name marks ");
for(i=0;i<n;i++)
{
scanf("%d%c%f",&s[i].no,&s[i].name,&s[i].marks);
}
return 0;
}
the program quits after entering one student details even I have selected number of students as 4 .
The inputs I am giving here as
[root#localhost raja]# gcc -o s s.c
[root#localhost raja]# ./s
enter number of students 4
enter student Number Name marks 1 as 12.03
[root#localhost raja]#
its quitting the program even after entering only 1st student details.
help me.
This is the correct code
# include <stdio.h>
struct student
{
int no;
char name[20];
float marks;
}s[10];
int main()
{
int i,n;
printf(" enter number of students ");
scanf("%d",&n);
printf(" enter student Number Name marks ");
for(i=0;i<n;i++)
{
scanf("%d%20s%f",&s[i].no,s[i].name,&s[i].marks);
}
return 0;
}
The first error is %c should be %s cause you are expecting a string and not a character.
The second is that when you are expecting %s you just need to pass in the variable name since its an array and therefore is a pointer.
20 before the s specifies the width allowed for the string for the name variable. If the length of the input string for name exceeds 20, it will mess up the input of the other variables and program will terminate or give unexpected behaviour.
This:
scanf("%d%c%f"
Should be more like this:
scanf("%d %s %f"
The wrong here :
scanf("%d%c%f",&s[i].no,&s[i].name,&s[i].marks);
The right answer is :
scanf("%d%s%f",&s[i].no,&s[i].name,&s[i].marks);

Resources