How to use int in array? - c

i create a really simple coding and it got no errors but when it run, i cant put input in the 'age' side.
#include <stdio.h>
#include <conio.h>
struct baby
{
char name[2][30];
char sex[2][7];
char birthday[2][12];
};
struct parents
{
char nama[2][30];
int age[2];
};
struct momdad
{
struct parents father;
struct parents mother;
};
struct momdad info;
struct baby newborn;
int main()
{
int i;
for(i=0;i<2;i++)
{
printf("\nEnter baby's name %d: ",i+1);
gets(newborn.name[i]);
printf("Enter baby's sex %d (Female/Male): ",i+1);
gets(newborn.sex[i]);
printf("Enter baby's birthday %d (dd/mm/yyyy): ",i+1);
gets(newborn.birthday[i]);
printf("Enter father's name %d: ",i+1);
gets(info.father.nama[i]);
printf("Enter father's age %d: ",i+1);
gets(info.father.age[i]);
printf("Enter mother's name %d: ",i+1);
gets(info.mother.nama[i]);
printf("Enter mother's age %d: ",i+1);
gets(info.mother.age[i]);
}
printf("\n\n\tNEW BORN BABY IN KUANTAN HOSPITAL");
printf("\n\n===============================================");
for(i=0;i<2;i++)
{
printf("\n\nBaby name: %s",newborn.name[i]);
printf("\nSex: %s",newborn.sex[i]);
printf("\nBirthday: %s",newborn.birthday[i]);
printf("\n\nFather name: %s",info.father.nama[i]);
printf("\nFather age: %s",info.father.age[i]);
printf("\n\nMother name: %s",info.mother.nama[i]);
printf("\nMother age: %s",info.mother.age[i]);
printf("\n\n----------------------------------------------");
}
getch();
}
this is my declaration that i think is wrong but i dont know how.
int age[2];
and the input will be putting in here
printf("Enter father's age %d: ",i+1);
gets(info.father.age[i]);
n in here
printf("Enter mother's age %d: ",i+1);
gets(info.mother.age[i]);
i'm still new in programming sorry for asking this simple question

Never use gets(). It cannot be used safely, and as of 2011 it's been removed from the language.
In a comment, you mention calling fflush(stdin);. The behavior of fflush is undefined for input streams. Some implementations define the behavior, but depending on that will make your program non-portable -- and you don't need it anyway.
The simplest way to read input data is to use scanf(), but that has some of its own problems. For example, if you use scanf("%d", &n); and type 123, it will consume the 123 and leave anything following it (such as a newline) waiting to be read.
A better way to read input is to use fgets to read a line of text, then sscanf to parse the data from the input line. It re
Here's an example:
#define MAX_LEN 200
char line[MAX_LEN];
int num;
printf("Enter an integer: ");
fflush(stdout);
if (fgets(line, MAX_LEN, stdin) == NULL) {
fprintf(stderr, "Error reading line\n");
exit(EXIT_FAILURE);
}
if (sscanf(line, "%d", &num) != 1) {
fprintf(stderr, "Error parsing integer from line\n");
exit(EXIT_FAILURE);
}
printf("The number is %d\n", num);
I call fflush(stdout) after the first printf to ensure that the prompt actually appears. stdout can be line-buffered, meaning that output won't appear until you've printed an entire line. The fflush isn't always necessary, but it's a good idea.
The fgets call reads a full line of input or MAX_LEN characters if the line is longer than that. (gets has no way to specify the maximum input size, so no matter how big your target array is, it can always read more and clobber random memory.) fgets returns a null pointer if there was a problem, and I check for that.
sscanf is similar to scanf, but it reads data from a string in memory, not from standard input. (There's also fscanf, which reads from a specified file.) It returns the number of items that it successfully scanned, so a value other than 1 would indicate an error.
I suggest reading the documentation for all these functions; I haven't covered everything they do. In fact, you should read the documentation for any standard library function you use.

Related

Why value of a state array is not showing in the output in C Program?

I'm making a C program in which it'll ask full name and address from the user and the program should give output like this:
Priya Shah
100,mainstreet
city,subdistrict
gujarat,382007
But program is giving output like this:
Priya Shah
100,mainstreet
city,subdistrict
,382007
#include <stdio.h>
void main(){
char fname[10],lname[30];
char house_no[5],street[40],city[30],taluka[20],state[70]="state",pin[6];
printf("Enter your Full Name: ");
scanf("%s %s",fname,lname);
printf("Enter your Address: (Format of Address is: HouseNo,Street,City,Taluka,State-pin) ");
scanf("%s %s %s %s %s %s",house_no,street,city,taluka,state,pin);
printf("%s %s\n%s,%s\n%s,%s\n%
s,%s",fname,lname,house_no,street,city,taluka,state,pin);
}
I have also initialised the state array then also it is not showing in the output
I understand your question and i would like to tell that every string has a null character which consume one block of space and in your case . you wrote pin[6] and you want enter a pin code , like 110010 it is already 6 character but string automatically add null character so in this case you need to replace pin[6] with pin[7]
thank you.......
pin[6] is too short to store 6-character strings like 382007. A room for terminating null-character is required. It looks like st happened to be placed after pin and its data is destroyed due to the out-of-range write.
Allocate enough elements and specify the maximum number of characters to read to prevent buffer overrun. Also you should check the return values of scanf() to check if it succeeded to read all required things.
#include <stdio.h>
int main(void){
char fname[10],lname[30];
char house_no[5],street[40],city[30],taluka[20],st[70]="state",pin[20];
printf("Enter your Full Name: ");
if (scanf("%9s %29s",fname,lname) != 2){
fputs("read error\n", stderr);
return 1;
}
printf("Enter your Address: (Format of Address is: HouseNo,Street,City,Taluka,State-pin) ");
if(scanf("%4s %39s %29s %19s %69s %19s",house_no,street,city,taluka,st,pin) != 6){
fputs("read error\n", stderr);
return 1;
}
printf("%s %s\n%s,%s\n%s,%s\n%s,%s",fname,lname,house_no,street,city,taluka,st,pin);
}

After getting user inputs the last printf() is not printing at all

Struggling on my homework assignment.
After I give inputs it stops rather than doing the random array and last print if anyone can help I would appreciate it
#include <stdio.h>
#include <stdlib.h>
int main() {
char name, color;
int age;
int *poer = &age;
char *p = &name;
char *ptr = &color;
printf("What is your name?\n");
scanf(" %s", &name);
printf("How old are you??\n");
scanf(" %d", &age);
printf("What is your favorite color?\n");
scanf(" %s", &color);
char *story[5] = {"old volkswagen beetle", "singlet", "quater", "left sock",
"blackberry bold ninek"};
srand(time(0));
printf("My pal right here %s is %d years old I feel like we have been coding"
" together for a hundred years now I always wonder where the time has gone"
" One thing I have wanted to know is why they love "
"their %s %s so much I guess I might never know\n",
name, age, color, story[rand() % 5]);
return 0;
}
Plenty of errors can be caught by enabling the compiler warnings.
Here is the list of all problems with their proper solutions:
For this line:
srand(time(0));
You need to include the time.h library, otherwise, you will get an implicit definition of time() error message. Passing NULL to time() is a good practice.
As people figured out:
char name, color;
A single char-type cannot hold more than a single ASCII character. Thus, you need to formulate a sequence of characters, called character array. In C99, variable-length arrays are supported. Still, using a macro constant for defining string lengths during compile-time makes the code good. Replace it:
#define MAX_LENGTH 128 // Prefer your length
...
char name[MAX_LENGTH], color[MAX_LENGTH];
In the similar lines:
printf("What is your name?\n");
scanf(" %s", &name);
scanf() function stops reading further input after whitespace. For example, if you input: John Doe, the name will only store John, Doe becomes truncated. Also, never put an ampersand sign for a char-array in scanf().
fgets() is considered safer than this, since it accepts a limited number of characters defined in its second argument. Replace the scanf():
// ... , sizeof name, ... --- is also applicable here
if (fgets(name, MAX_LENGTH, stdin) == NULL) {
// Do something when input's invalid
}
// Input is okay
Note: The fgets() leaves a trailing newline character as soon as it stops receiving user input. To discard this, use this after its usage:
name[strcspn(name, "\n")] = 0;
After applying all these changes, you will not get any further problems.
the following code will be fine
char name[256];
char color[256];
int age;
printf("What is your name?\n");
scanf(" %s", name);
printf("How old are you??\n");
scanf(" %d", &age);
printf("What is your favorite color?\n");
scanf(" %s", color);
in your code, a char was casted to char* the variable will hold data larger than it could. the the stack was ruined
You used char for string which is wrong. You need a char array to store the strings.
Try this:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define STR_MAX 300
int main()
{
char name[STR_MAX];
char color[STR_MAX];
int age;
printf("What is your name?\n");
scanf(" %s", name);
printf("How old are you??\n");
scanf(" %d", &age);
printf("What is your favorite color?\n");
scanf(" %s", color);
char *story[5] = {"old volkswagen beetle","singlet","quater","left sock","blackberry bold ninek"};
srand(time(0));
printf("My pal right here %s is %d years old I feel like we have been coding together for a hundred years now I always wonder where the time has gone One thing I have wanted to know is why they love their %s %s so much I guess I might never know\n",name, age, color, story[rand()%5]);
return 0;
}
your program terminated abnormally because stack was ruined.
char name; //has only 1 byte space
char color; //has only 1 byte space
but these two variables was used to hold data larger than they can. then data was written to some place else which will cause the stack overflow.
code like this will be ok
char name[256];
char color[256];

User Input being skipped

still making my way through C Programming Absolute Beginner's Guide.
I am at the example about Structures and I cannot figure out what is going wrong. When I compile and run the code, the first two questions run fine, but after it prompts for "How much did the book cost?", when I enter the input for this one, the next two questions get posted together. I have no idea why. I think I have the code written as shown in the book. I have read online that gets is not code but I am not sure why at this point. Any guidance would once again be greatly appreciated!
//This header file defines a structure for information about a book
struct bookInfo {
char title[40];
char author[25];
float price;
int pages;
};
/*This program gets the bookInfo structure by including structurePractice.h
and asks the user to fill in three structures and then prints them*/
//First, include the header file
#include "structurePractice.h"
#include <stdio.h>
int main()
{
int ctr;
struct bookInfo books[3]; //Array of 3 structure variables
//Get information about each book from the user
for (ctr = 0; ctr < 3; ctr++)
{
printf("What is the name of the book #%d?\n", (ctr+1));
gets(books[ctr].title);
puts("Who's is the author? ");
gets(books[ctr].author);
puts("How much did the book cost? ");
scanf(" $%f", &books[ctr].price);
puts("How many pages are in the book? ");
scanf(" %d", &books[ctr].pages);
getchar(); //Clears last newline for next loop
}
//Print a header line and then loop through and print the info
printf("\n\nHere is the collection of books: \n");
for (ctr = 0; ctr < 3; ctr++)
{
printf("#%d: %s by %s", (ctr+1), books[ctr].title, books[ctr].author);
printf("\nIt is %d pages and costs $%.2f", books[ctr].pages, books[ctr].price);
printf("\n\n");
}
return (0);
}
You have a typo in your scanf.
scanf(" $%f", &books[ctr].price);
^
|
here
That says you want a $ followed by a decimal number. If the user does not input a dollar sign, scanf will read nothing. The input will remain on the input buffer. It will be read by the next scanf.
This is one of the many problems with scanf. Because scanf mixes up reading input with parsing input, if the input does not match the expected format it will remain in the input buffer. Instead, read and parse separately with fgets (not gets) and sscanf. It's also important to check that the input was read else books[ctr].price will contain garbage.
// Declare a buffer once outside the loop. Reuse it for each fgets call.
// BUFSIZ is a constant for the natural I/O buffer size of your platform.
char buf[BUFSIZ];
puts("How much did the book cost? ");
// Read only as much as the buffer can handle. This is what makes fgets safe,
// and gets unsafe.
fgets(buf, sizeof(buf), stdin);
// sscanf returns the number of items matched. Check if they all matched.
if( sscanf(buf, " %f", &books[ctr].price) != 1) {
printf("Sorry, '%s' doesn't look like a price.", buf);
// Set it to something or else it will be garbage.
books[ctr].price = 0;
}
A real program would loop until it gets valid input. The important thing is to read the buffer, then parse it, and check if the parsing worked. Later on you might write a little function to package up this prompting code.

Reading in a list

I've to code a program that reads in a list of student's names and ids and sort them based on first name, last name, and id. But there are currently two problem with my code.
#include <stdio.h>
int main() {
char firstName[200][21], lastName[200][51];
unsigned short id[200]; // used short to decrease memory usage
int i;
for (i=0; i<200; ++i) {
printf("Enter first name of student %d: ",i+1);
getchar(); // FIX to consume enter
fgets(firstName[i],21,stdin);
printf("Enter last name of student %d: ",i+1);
fgets(firstName[i],21,stdin);
printf("Enter student number of student %d: ",i+1);
scanf("%hu",&id[i]);
printf("You've entered %s %s with ID %hu",firstName[i],lastName[i],id[i]);
}
// other functions to do after reading in the data is successfully done
}
Reading in the values must be stopped if students reach 200 or if the user enters EOF.
Student's First Name or Last Name might consist of multiple parts (something like "john john" so I used fgets instead of scanf and %s to read in the word which comes after space as well but it fails and only last name is stored.
Could you tell me how to stop the loop with EOF and read in the first and last name correctly? Thanks.
for checking the EOF , you can use function:
feof(FILE*) // if it returns 1 then it is EOF reached.
you can use it like the below snippet :
if (feof(fp) == 1)
break;
and the 2nd problem :
printf("Enter last name of student %d: ",i+1);
fgets(firstName[i],21,stdin); // this is incorrect.
use 'lastname' instead of 'firstname'. It should be like this :
fgets(lastName[i],21,stdin);
in this way you are overwriting the value of firstname

Why gets() function skips when preceded by scanf("%d")?

I want to make a program which take Roll No and Full name as input and simply display it
My code is . this code skip scaning value of n through gets function. Why this error occur and how to over come this?
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
char n[30];
printf("enter your roll no");
scanf("%d",&r);
printf("enter your full name");
gets(n);
printf("roll no is %d ",r);
printf("name is %s ",n);
getch();
}
while the below code scan the first gets value and skips the second one.
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
char n[30], f[30];
printf("enter your roll no");
scanf("%d",&r);
printf("enter your full name");
gets(n);
printf("enter your full name of your father ");
gets(f);
printf("roll no is %d ",r);
printf("name is %s ",n);
printf("father name is %s ",f);
getch();
}
The code DOES NOT skip scanning the value of 'n'.
I believe that when you run the program, you enter the Roll No and then press the ENTER key on your keyboard.
This is the cause.
As soon as you press the ENTER key, the escape sequence '\n' is saved in the array n. Your gets() command is executing perfectly.
In the second case, the variable 'n' stores the escape sequence and the next variable 'f' takes the string you enter next.
To make your code work just enter your scanf statement like this:-
scanf("%d ",&r);
Notice the space after %d.
Try this code-
#include<stdio.h>
int main(void)
{
int r;
char n[30], f[30];
printf("Enter your roll no");
scanf("%d ",&r); // I have inserted a space after %d
printf("Enter your full name");
gets(n);
printf("Enter your full name of your father ");
gets(f);
printf("\nRoll no is %d ",r);
printf("\nName is %s ",n);
printf("\nFather name is %s ",f);
return 0;
}
TIP:- You must try not to use gets() and puts()
You can read more about it here.
The simple solution for the problem is to add fflush(stdin); between scanf(); and gets();
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
char n[30],fn[30];
clrscr();
printf("\nEnter roll ");
scanf("%d",&r);
fflush(stdin);
printf("\nEnter name ");
gets(n);
printf("\nEnter father name ");
gets(fn);
printf("\n\nRoll %d",r);
printf("\nname %s",n);
printf("\nfather name %s",fn);
getch();
}
Using scanf instead of gets will solve your problem:
scanf("%s", n); // Read in your name
Please note that when reading in any string like this you should use safe functions that are passed the length of the string (for example scanf_s from MSDN).
I don't know why it gets skipped but what you could do to avoid any other confusion like fflush(stdin) or fgets etc etc.
Just use gets(string) on the next line. So when it skips the first gets command it goes onto the other one.
Try that
Cheers,
;)
I just had the same problem two hours ago, but to solve this situation easily, all you have to fo is to add a "getchar()" after the "scanf()" and before the "gets()", so that the extra "\n" goes to the "getchar()" and you can type as you want in the next "gets()".
I was also facing the same problem as mentioned above.. so with the help of the answers mentioned here and using hit and trial method, I found that when we press enter after giving input to any variable using scanf(), \n is stored in the next gets() function.. and next time it doesn't take any input from the keyboard.. so to avoid this just use getchar() in between the scanf() nd gets() nd also remember that getchar() takes only 1 character.. so don't give any extra input to scanf() as again this will be stored and will be used in gets() nd the problem will remain the same....
hope this will help..
thank u..

Resources