C program using structs isn't working properly - c

I'm attempting to create a simple program that stores ten "pets" into an array. Each stuct contains data that must be accessed through functions. For some reason this doesn't seem to be working the way I would expect. Does anyone know why the program prompts for the name and then runs through the rest of the program without prompting the user again?
#include<stdlib.h>
#include<stdio.h>
#include <string.h>
struct Pet {
char name[50]; //name
char type[50]; //type
char owner[50]; //owner
};
void setPetName(struct Pet *pet, char *name){
memcpy(pet->name,name, 50);
}
void setPetType(struct Pet *pet, char *type){
memcpy(pet->type,type, 50);
}
void setOwner(struct Pet *pet, char *owner){
memcpy(pet->owner,owner, 50);
}
char* getName(struct Pet *pet){
return pet->name;
}
char* getType(struct Pet *pet){
return pet->type;
}
char* getOwner(struct Pet *pet){
return pet->owner;
}
void printPetInfo(struct Pet *pet){
printf("Pet's name is %s, Pet's type is %s, Pet's owner is %s", pet->name, pet->type, pet->owner);
}
int main(){
struct Pet Pets[9];
int index;
char name[50], type[50], owner[50];
for (index=0; index<9; index++){
struct Pet pet;
printf("Please enter pet's name ");
scanf("%s\n", name);
setPetName(&pet, name);
printf("Please enter pet's type ");
scanf("%s\n", type);
setPetType(&pet, type);
printf("Please enter pet's owner ");
scanf("%s\n", owner);
setOwner(&pet, owner);
printPetInfo(&pet);
Pets[index]=pet;
}
return 0;
}

First you can't hold a string in a char:
char name, type, owner;
Instead you need an array of char (ie char name[50]; for example)
Then the format to scan a string is %s, not &s
scanf("&s\n", name);
And finally if you want to print a string, use format %s, not %c (%c is to print a single char).

Related

How to return an int value in C?

I am new to C language and trying to create a simple program to return name and age. I created a working function for returning the name but this does not work for returning the int.
The code I have now is:
int * GetAge(){
int Age;
printf("What is your age: ");
scanf(" %d", &Age);
int * returnedage = Age;
return returnedage;
}
This is GetName():
char * GetName(){
char Name[31];
printf("What is your name: ");
scanf("%s", Name);
char * returnedname = Name;
return returnedname;
}
The warning is on this line:
int * returnedage = Age;
It says:
incompatible integer to pointer conversion
initializing 'int *' with an expression of type 'int'; take
the address with &
I have tried:
int * returnedage * Age;
int * returnedage & Age;
//for strcpy I set the function as a char
char * returnedage;
strcpy(Age, returnedage);
None of these work.
I want to just get the name and age then in main I am printing the name and age with:
printf("Your name is %s and your age is %d", GetName(), *GetAge());
This does not have any errors.
So my expected Output is:
What is your name: Ethan
What is your age: 13
Your name is Ethan and your age is 13
What I actually get is:
What is your name: ethan
What is your age: 13
exit status -1
Please tell me if there is a basic solution for this.
Change your code to this:
int GetAge()
{
int Age;
printf("What is your age: ");
scanf(" %d", &Age);
return Age;
}
On main (Remove the * on the GetAge()):
printf("Your name is %s and your age is %d", GetName(), GetAge());
You have overcomplicated things. Read again the sources you are using to learn C to understand better what is going on.
Edited:
Change your GetName() to:
void GetName(char *name){
printf("What is your name: ");
scanf("%s", name);
}
Now on main:
char name[31];
GetName(name);
printf("Your name is %s and your age is %d", name, GetAge());
The reason for that is that C can not return an array of characters (this is what you are trying to accomplish somehow). Instead, you can give that function the memory address of a local variable which lives in main() and store the user's input into that variable.
Try:
int GetAge()
{
int Age;
printf("What is your age: ");
if (scanf("%d", &Age) != 1)
return -1; // return an error code if an integer couldn't be read
return Age;
}
Now call the function using GetAge().

writing in a file using structures

I wrote a code that is supposed to write into a file but when i execute the program it says "error in saving student data".Here is the code.
#include<stdio.h>
typedef struct Student{
int numberOfStudents;
char name; // onoma foithth
char surname; // epi8eto foithth
};
int main(){
struct Student s1;
FILE *file=fopen("d:\\student.txt","w");
if(file==NULL){
printf("error in saving student data");
return 1;
}
while(1){
printf("Enter number of students: ");
scanf("%d",&s1.numberOfStudents);
printf("enter name: ");
scanf("%s",&s1.name);
printf("enter surname: ");
scanf("%s",&s1.surname);
fprintf(file,"%d\t%s\t%s\n",s1.numberOfStudents,s1.name,s1.surname);
printf("continue (Y/N)");
char ch=getch();
if (ch=='N' || ch=='n')
break;
}
fclose(file);
return 0;
}
I have searched but i can't find the problem.where is my mistake?
name field of structure should be char array if you want to store onoma foithth in that as shown. modify your structure as
typedef struct Student{
int numberOfStudents;
char name[10]; // onoma foithth
char surname; // epi8eto foithth
};
and then while scanning name remove & because name is itself address.
scanf("%s",s1.name);
Make sure you gave correct path in fopen()

passing argument 2 of strcpy makes pointer from integer without a cast

this is the whole code of what im doing, im trying to create a song library that will put what the user enter into file. now the compiler says that passing argument 2 of strcpy makes pointer from integer without a cast and i dont know why. also can u check my linked list for the struct. im so noob at linked list :(
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct node {
//definition of struct node to create struct node song
int SongID;
char Title[100];
char Artist[100];
char Composer[100];
char Album[100];
char Genre[100];
int Rating;
char Remarks[1000];
struct node*next;
};
add_song(int SongID, char Title, char Artist, char Composer, char Album, char Genre, int Rating, char Remarks) {
//this is the add song function as stated in the mp2 specs
FILE*fp;
fp=fopen("song.txt","r+");
int i=1, j, choice;
struct node* temp=malloc(sizeof(struct node));
temp->SongID=SongID;
fprintf(fp,"%d",SongID);
strcpy(temp->Title, Title);
fprintf(fp,"%s",Title);
strcpy(temp->Artist, Artist);
fprintf(fp,"%s",Artist);
strcpy(temp->Composer, Composer);
fprintf(fp,"%s",Composer);
strcpy(temp->Album, Album);
fprintf(fp,"%s",Album);
strcpy(temp->Genre, Genre);
fprintf(fp,"%s",Genre);
temp->Rating=Rating;
fprintf(fp,"%d",Rating);
strcpy(temp->Remarks, Remarks);
fprintf(fp,"%s",Remarks);
fclose(fp);
}
int main ()
{
struct node song;
int choice;
int k, i;
int SongID;
char Title[100];
char Artist[100];
char Composer[100];
char Album[100];
char Genre[100];
int Rating;
char Remarks[1000];
/* do
{
printf("Enter 1 to add song, 2 to update song, or 3 to list songs: ");
scanf("%d\n", &choice1);
if (choice1==1)
{*/
srand(time(NULL));
song.SongID=rand();
printf("Enter Title: ");
fgets(Title,100,stdin);
printf("Enter Artist: ");
fgets(Artist,100,stdin);
printf("Enter Composer: ");
fgets(Composer,100,stdin);
printf("Enter Album: ");
fgets(Album,100,stdin);
//for easier code, numbers are being chosen as input
printf("Press 1 for Art Music, 2 for Popular Music, or 3 for Traditional Music): ");
scanf("%d", &choice);
if (choice==1)
{
strcpy(song.Genre,"Art Music");
}
else if (choice==2)
{
strcpy(song.Genre,"Popular Music");
}
else if (choice==3)
{
strcpy(song.Genre,"Traditional Music");
}
else
{
printf("You entered a blank genre.\n");
}
printf("Enter your rating, choose from 1-5: ");
scanf("%d", &Rating);
printf("Enter Remarks: ");
fgets(Remarks,1000,stdin);
add_song(SongID, Title, Artist, Composer, Album, Genre, Rating, Remarks);
/*k=0;
break;
}
else if (choice1==2)
{
//update_song(song);
k=0;
break;
}
else if (choice1==3)
{
// list_songs(song);
k=0;
break;
}
else
{
k=1;
printf("That is not a valid input.\n");
}
}while (k==1);*/
return 0;
}
Your function definition don't match with the arguments you pass. It should be
void add_song(int SongID, char *Title, char *Artist, char *Composer, \
char *Album, char *Genre, int Rating, char *Remarks) {
...
...
}
Another issue is that songID is uninitialized in main(). Reading from an uninitialized variable is undefind behaviour.
Another problem you might face is that fgets() reads the newline \n into buffer if there's space available which might be problematic.
Something to be aware of and you need trim it if nececcary.
This is working copy of your code except one thing "Remark". Before executing scanf for Remark process exits . Change your arguments as I did here and also change fopen mode as +w so if file is not exist it can be created automatically. strcpy prototype is `char *strcpy(char *dest, const char *src).
So I have changed accordingly
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct node {
//definition of struct node to create struct node song
int SongID;
char Title[100];
char Artist[100];
char Composer[100];
char Album[100];
char Genre[100];
int Rating;
char Remarks[1000];
struct node *next;
};
void add_song(int SongID, char *Title, char *Artist, char *Composer, char *Album, char *Genre, int Rating, char *Remarks) {
//this is the add song function as stated in the mp2 specs
FILE *fp;
fp=fopen("song.txt","a+");
int i=1, j, choice;
struct node* temp=malloc(sizeof(struct node));
temp->SongID=SongID;
fprintf(fp,"%d",SongID);
strcpy(temp->Title, Title);
fprintf(fp,"%s",Title);
strcpy(temp->Artist, Artist);
fprintf(fp,"%s",Artist);
strcpy(temp->Composer, Composer);
fprintf(fp,"%s",Composer);
strcpy(temp->Album, Album);
fprintf(fp,"%s",Album);
strcpy(temp->Genre, Genre);
fprintf(fp,"%s",Genre);
temp->Rating=Rating;
fprintf(fp,"%d",Rating);
strcpy(temp->Remarks, Remarks);
fprintf(fp,"%s",Remarks);
fclose(fp);
}
int main ()
{
struct node song;
int choice;
int k, i;
int SongID;
char Title[100];
char Artist[100];
char Composer[100];
char Album[100];
char Genre[100];
int Rating;
char Remarks[1000];
/* do
{
printf("Enter 1 to add song, 2 to update song, or 3 to list songs: ");
scanf("%d\n", &choice1);
if (choice1==1)
{*/
srand(time(NULL));
song.SongID=rand();
printf("Enter Title: ");
fgets(Title,100,stdin);
printf("Enter Artist: ");
fgets(Artist,100,stdin);
printf("Enter Composer: ");
fgets(Composer,100,stdin);
printf("Enter Album: ");
fgets(Album,100,stdin);
//for easier code, numbers are being chosen as input
printf("Press 1 for Art Music, 2 for Popular Music, or 3 for Traditional Music): ");
scanf("%d", &choice);
if (choice==1)
{
strcpy(song.Genre,"Art Music");
}
else if (choice==2)
{
strcpy(song.Genre,"Popular Music");
}
else if (choice==3)
{
strcpy(song.Genre,"Traditional Music");
}
else
{
printf("You entered a blank genre.\n");
}
printf("Enter your rating, choose from 1-5: ");
scanf("%d",&Rating);
printf("Enter Remarks: \n");
fgets(Remarks,1000,stdin);
add_song(SongID, Title, Artist, Composer, Album, Genre, Rating, Remarks);
/*k=0;
break;
}
else if (choice1==2)
{
//update_song(song);
k=0;
break;
}
else if (choice1==3)
{
// list_songs(song);
k=0;
break;
}
else
{
k=1;
printf("That is not a valid input.\n");
}
}while (k==1);*/
return 0;
}
Didn't go through the whole code, but strcpy problem is obvious. According to definition of function strcpy (http://www.tutorialspoint.com/c_standard_library/c_function_strcpy.htm), it expects two char pointers (aka strings in C)
char *strcpy(char *dest, const char *src)
You're passing only char arguments to a function add_song, which is just not the pointer. Change the signature of the function add_song and then you should be fine with strcpy

Just first alphabet is showing in the output.[char type]

When I give the input then only first alphabet is showing.
I want to print the complete name which is I just entered.
#include <stdio.h>
int main()
{
char name;
char grades;
int i;
printf("Name of the Student:");
scanf("%c",&name);
printf("Name your Just entered is : %c",name);
return 0;
}
I agree with the others - but add some error checking and ensure no buffer overruns i.e
#include <stdio.h>
int main() {
char name[101];
printf("Name of the student:");
if (scanf("%100s", &name) == 1) {
printf("Name you just entered: %s\n", name);
return 0;
} else {
printf("Unable to read name of student\n";
return -1;
}
}
EDIT
As you have edited the question so that it does not have the same meaning as before I will leave my previous solution here.
But what you want is to use fgets - this allows for white space in the name
ie.
#include <stdio.h>
int main()
{
char name[100];
printf("Name of student:");
fflush(stdout);
fgets(name, 100, stdin);
printf("Students name is %s\n", name);
return 0;
}
Replace char name; with char name[100];. This will define name as array of chars, because you handled with it as single character.
For scanf replace it with scanf("%s",&name[0]);, and printf with printf("Name your Just entered is : %s",name);. %s means string, so it will scan whole string, not just single character. In scanf &name[0] points to beginning of array.
You need to scanf into an array, rather than into a single character:
#include <stdio.h>
int main() {
char name[100];
printf("Name of the student:");
scanf("%s", &name);
printf("Name you just entered: %s\n", name);
}
You are trying to store a array of characters(string) in a character. So only the first character is taken.To rectify this initialize the name as:
char name[40];
take input as :
scanf("%s",name);
and print as:
printf("name is %s",name);
name is a char and scanf will only catch one character when you use %c. You can use a char array to store the name instead :
char name[40];
/* edit the size for your need */
Also edit your scanf and printf to use a %s
You are reading (and printing) a single char using %c. If you want to handle stirngs, you should use a char[] and handle it with %s:
#include <stdio.h>
int main()
{
char name[100]; /* Assume a name is no longer than 100 chars */
char grades;
int i;
printf("Name of the Student: ");
scanf("%s",&name);
printf("Name your Just entered is : %s",name);
return 0;
}

displaying numbers and strings from a structure in c

#include <stdio.h>
#include <string.h>
struct Directory {
char Name;
long int Number;
int HouseNumber;
char street;
};
int main(void)
{
struct Directory contact;
struct Directory *answer1, *answer2, *answer3, *answer4;
char answer;
printf("Welcome to Telephone Directory.\n\nPlease enter the name of the contact.\n");
scanf("%s", &contact.Name);
printf("Please enter the number of the contact.\n");
scanf("%ld", &contact.Number);
printf("Please enter the address of the contact.\n");
scanf("%d %s", &contact.HouseNumber, &contact.street);
answer1 = &contact;
answer2 = &contact;
answer3 = &contact;
answer4 = &contact;
printf("Would you like to obtain information on your contact? Enter 'yes' or 'no'.\n");
scanf("%s", &answer);
if (strcmp(&answer, "yes")==0) {
printf("%s\n", &answer1->Name);
printf("%ld\n", answer2->Number);
printf("%d", answer3->HouseNumber);
printf("%s", &answer4->street);
}
if (strcmp(&answer, "no")==0) {
printf("Thank you for using Telephone Directory.\n");
}
}
I'm trying to make a contacts program in C. I want the program to print the user's house address. I have the "HouseNumber" variable in the structure and the "street" variable in the structure, setting "answer3" as an int variable to display the "HouseNumber" and "answer4" as a char variable to display "street". Together, I was hoping they will print the user's address in a single string, but when I run the program and enter "yes" to display the contact information after entering the house number and street, the program crashes, and displays lldb with a bad thread error. It seems like everything is right, because my compiler says that there are no issues with the code, but it crashes. Can somebody please help me with this?
When you do scanf("%s", &answer);
You're writing the user's input into a char answer; The argument to scanf needs to have enough space to hold the entire string plus one null byte. Try something like:
char answer[256];
This assumes that input will never be more than 256 chars, but seems reasonable in a simple program like this. Note that gcc supports non-standard %a that will allocate a string for you if you pass in a char*.
When you try to store strings you need to ensure there's enough space for the data you're putting there, like in Dictionary only holding a char, or else you're going to overflow and stomp on some other memory you may need later.
The mistake i have observed in your code is, you have created name,street and answer variables as char but tried to store strings in them by using %s resulting into crashing. In those places either you have to use char * or character array.
char *name //(or) char name[15]
The modified code looks like this
#include <stdio.h>
struct Directory {
char Name[20];
long int Number;
int HouseNumber;
char street[20];
};
int main(int argc, char *argv[])
{
struct Directory contact;
struct Directory *answer1, *answer2, *answer3, *answer4;
char answer[4];
printf("Welcome to Telephone Directory.\n\nPlease enter the name of the contact.\n");
scanf("%s", contact.Name);
printf("Please enter the number of the contact.\n");
scanf("%ld", &contact.Number);
printf("Please enter the address and street of the contact.\n");
scanf("%d %s", &contact.HouseNumber, contact.street);
answer1 = &contact;
answer2 = &contact;
answer3 = &contact;
answer4 = &contact;
printf("Enter yes r no");
scanf("%s",answer);
if (strcmp(answer,"yes")==0) {
printf("%s\n", answer1->Name);
printf("%ld\n", answer2->Number);
printf("%d\n", answer3->HouseNumber);
printf("%s", answer4->street);
}
else {
printf("Thank you for using Telephone Directory.\n");
}
return 0;
}
struct Directory {
char * Name;
long int Number;
int HouseNumber;
char * street;
};
inside main:
struct Directory Contact;
Contact.Name = malloc(sizeof(char * sizeOfName));
scanf("%s", contact.Name);
Then you can copy in your Name/street etc.
Since Name is a char*, you won't use the address, but you'll just pass the pointer to scanf. This will fill that malloc'd memory with the string the user enters.

Resources