displaying numbers and strings from a structure in c - 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.

Related

How can I print the registration number of student according to his/her department and school

Getting issue while solving this problem for assignment of C programming:
Need to create an app for college where there are 500 undergraduate students from which 250 are in School of Engineering (SOE) and 250 are in School of Science (SOE) , where suppose if a student belongs to Computer engineering (CE) batch 2020_21:
supposed output needs too look like:
SOEUNGCE0001 - SOEUNGCE0040
departments in school of engineering are:
chemical engineering -CHE
computer engineering -CE
mechanical engineering- ME
Environmental engineering -ENE
Electrical Engineering - EE
and in school of science:
Architecture -AR
computer science-CS
Biotechnology-BT
Pharmacy-PH
I tried printing with switch case statements but it's wasn't working with strings. also the below program is having some issue i.e. it doesn't take some inputs.
HELP ME SOLVE THIS.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char name;
int roll_no;
char department;
char school;
}students;
int main()
{
students student;
//inputs
printf("Enter Name : " );
scanf("%s", &student.name);
printf("\nRoll Number : ");
scanf("%d", &student.roll_no);
printf("\nDepartment : ");
scanf("%s",&student.department);
printf("\nSchool : ");
scanf("%s",&student.school);
if (student.department == 'Chemical')
{
printf("Name : %s \t",student.name);
printf("\n%sUNG%s00%d", student.school, "CHE", student.roll_no);
}
return 0;
}
You have 3 mistakes:
Logical Error: since name, department and school are strings, so they must be arrays of characters i.e char name[100]. So the structure should be modified as the following:
typedef struct{
char name[100];
int roll_no;
char department[100];
char school[100];
}students;
2- After editing the structure you will get warning from the compiler since scanf takes the address of the element to be scanned and student.name points to the first character of the string name. So Edit the scanf arguments to be :
scanf("%s", student.name);
.
scanf("%s", student.department);
.
scanf("%s", student.school);
Note: You can also use fgets instead of scanf to avoid buffer overflow but you have to consider that fgets includes the newline character, \n, within the string, so you have to replace the \n with \0. See tricks for how to replace the \n with \0
3- The last error is in comparing strings, you should use the strcmp function to compare between two strings, the function returns 0 if the two strings are typical. Also the string literals sholud be put inside double quotation marks "". So you should modify the last block to be :
if (!strcmp(student.department, "Chemical"))
{
printf("Name : %s \t",student.name);
printf("\n%sUNG%s00%d", student.school, "CHE", student.roll_no);
}
Try something like that:
typedef struct{
char name[100];
int roll_no;
char department[100];
char school[100];
} students;
int main() {
students student;
char input[100];
//inputs
printf("Enter Name : " );
fgets(student.name, 50, stdin);
printf("\nRoll Number : ");
fgets(input, 50, stdin);
sscanf(input,"%d", &student.roll_no);
printf("\nDepartment : ");
fgets(student.department, 50, stdin);
printf("\nSchool : ");
fgets(student.school, 50, stdin);
if (strcmp(student.department, "Chemical") == 0)
{
printf("Name : %s \t",student.name);
printf("\n%s %d", student.school, student.roll_no);
}
return 0;
}

I'm getting an Exception Error when using %S

int main()
{
int Age;
char Name;
//Age
printf("Type your age: ");
scanf_s("%d", &Age);
printf("Your age is %d\n", Age);
//Name
printf("Type your Name: ");
scanf_s("%s", &Name);
printf("Your name is %s", Name);
return 0; }
It's the 'Name' section which is throwing out an error. I can't figure out why.
UPDATE: I'm coding in Visual Studio. Therefore, "scanf_s" is essentially required.
The error is "Exception thrown at 0x5B49D4EC (ucrtbased.dll) in Project1.exe: 0xC0000005: Access violation writing location 0x001A0000. occurred"
Your problem is that char Name; can only store a single character. Your code is allowing the user to type in multiple characters which are being stored into Name causing a memory error.
Change char Name; to something like char Name[50] so that you can store up-to 49 characters plus the null byte.
Also you should use scanf_s() properly to avoid the error if the buffer (char array) ends up being too small.
Note, you should always check the return from scanf_s() so you know if the user entered valid data or not.
This code works correctly in Visual Studio:
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
int main()
{
int Age;
char Name[50];
printf("Type your age: ");
if(scanf_s("%d", &Age))
{
printf("Your age is %d\n", Age);
printf("Type your Name: ");
if (scanf_s("%s", Name, (unsigned)_countof(Name)))
{
printf("Your name is %s\n", Name);
}
else
{
printf("Name:: Invalid Input\n");
}
}
else
{
printf("Age:: Invalid Input\n");
}
return 0;
}
The problem is that you defined Name as a char - a single character - but you are trying to use it as a string (multiple characters).
To fix this you must either (a) define Name as an array of characters (which would be a string) - such as char Name[100]; or (b) as a pointer (such as char *Name;) - which would require you to malloc() the string before use and free() it after use.
Strings can be tricky, as they are basically just arrays of chars, but that requires you to either know, or find a way to know, how many characters will be in the string. You can read more about how to do that here, in the documentation for scanf_s, which gives this example:
char c[4];
scanf_s("%4c", &c, (unsigned)_countof(c)); // not null terminated
First off I would just use scanf(), not scanf_s().
Furthermore you need to cast your Name variable as a string, which is an array of characters as I have defined it below. Using just char Name, means you have created a variable with room for just one character.
Hope this helps :)
int main()
{
int Age;
char Name[10];
printf("Type your age: ");
scanf("%d", &Age);
printf("Your age is %d\n", Age);
//Name
printf("Type your Name: ");
scanf("%s", &Name);
printf("Your name is %s", Name);
return 0;
}
Fixed the problem by going to...
Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically.
Thanks for everyone's help :)

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;
}

C program using structs isn't working properly

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).

How to create a string-type variable in C

Question
How to declare a string variable in C?
Background
In my quest to learn the basics of c, I am trying to port one of my oldest python programs, Bob, to C. In the program, the script asks the user for information on him or herself, and then spits out responses. Almost all of these variables use raw_input for their information - the variables are strings. But, I have found no way to declare C variables.
Code
So far, I have tried to declare the variable as of type char and int. Here is the code, switch the type at your leisure.
int main(int argc, const char * argv[])
{
int name;
printf("What is your name?");
scanf("%s",&name);
printf("Your name is %s", name );
return 0;
}
Error Message
When I run this code, Xcode returns some weird stuff. This part of the globidty-gloop is highlighted.
0x7fff96d2b4f0: pcmpeqb(%rdi), %xmm0
Lasty, this Yahoo Answer said that I had to use something called a character array. It was posted 5 years ago, so I assumed that there was a better way.
EDIT
I am following the tutorial at C Programming.
char name[60];
scanf("%s", name);
Edit: restricted input length to 59 characters (plus terminating 0):
char name[60];
scanf("%59s", name);
The int your putting is not a string, a string looks like "char myString[20]".
Not like "int name", that's an integer and not a string or char. This is the code you want:
int main(int argc, const char * argv[])
{
char name[9999];
printf("What is your name?\n");
scanf("%s", name);
system("cls");
printf("Your name is %s", name);
return 0;
}
In C you can not direct declare a string variable like Java and other language. you'll have to use character array or pointer for declaring strings.
char a[50];
printf("Enter your string");
gets(a);
OR
char *a;
printf("Enter your string here");
gets(a);
OR
char a[60];
scanf("%59s",a);
TESTED ON XCODE
You can do so:
int main(int argc, const char * argv[])
{
int i;
char name[60]; //array, every cell contains a character
//But here initialize your array
printf("What is your name?\n");
fgets(name, sizeof(name), stdin);
printf("Your name is %s", name );
return 0;
}
Initialize the array, is good to avoid bug
for(i=0;i<60;i++){
name[i]='\0'; //null
}
Instead int is used for int number (1, 2, 3, ecc.); For floating point number instead you have to use float
C does not have a string variable type. Strings can be stored as character arrays (char variable type). The most basic example I would add up to the rest is:
int main()
{
char name[] = "Hello World!";
printf("%s",name);
return(0);
}
It's easy!
Just put this line below, atop of your main() function.
typedef string char*;
This allows you to create a string variable as you do with integers or characters in C. After that, your program should look like this:
#include <stdio.h>
typedef char* string;
int main(void) {
string a = "Hello";
printf("%s\n", a); // %s format specifier for String
return 0;
}
For a live demonstration, visit this REPL.it.
Normally we use "&" in scanf but you shouldn't use it before variable "name" here. Because "name" is a char array. When the name of a char array is used without "[]", it means the address of the array.
replace int name; to--. char name[60];
#include <stdio.h>
int main()
{
char name[648];
printf("What is your name?");
scanf("%s", name);
printf("Your name is %s", name );
return 0;
}

Resources