User Input to File - c

I'm creating a program that should create a structure of a list of people entered by the user; the only problem I'm having is getting the user input data to appear in the text file. Anyone know how to do this? Here is the code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct person{
char name[20];
int age;
struct person *next_ptr;
} PERSON;
int main (void){
struct person PERSON;
FILE *fp;
char ans, ch;
int ppl=0;
fp=fopen("person_struct", "w");
if(fp != NULL){
while(ppl<25){
printf("Would you like to add a person to the list? [y/n] ");
scanf("%c", &ans);
if(ans == 'y') {
printf("\nEnter a name:\n");
scanf("%s", PERSON.name);
fprintf(fp, "%s",PERSON.name);
printf("\nEnter age:\n");
scanf("%i", &PERSON.age);
fprintf(fp, " %i\n", PERSON.age);
}
else {
ppl=25;
}
ppl++;
}
fclose(fp);
}
printf("\n\n\n");
system("pause");
return 0;
}

Youe scanf statement is wrong you forgot ampersand & operator before PERSON.age its int
scanf("%i", PERSON.age);
^ & missing
correct is:
scanf("%i", &PERSON.age);
You have two scanf stamens in your code to inputs from user one for string to scan name.
scanf("%s", PERSON.name);
This is correct and No need of & before string. But age is int and to scan int.float you need to add & before variable that is why added ampersand & before PERSON.age.
ref: scanf
Second:
fputs(PERSON.age, fp); is wrong syntax of fputs is:
int fputs( const char *str, FILE *stream );
^ you are passing int
first argument should be const char* but your are passing int
fputs(PERSON.age, fp);
^ wrong , age is int not char*
When you need formatting input/output prefer printf and scanf functions, My suggestion change your read/write like: (read comments)
printf("Enter a name:\n");
scanf("%s", PERSON.name); // here is No & because `name` is string
scanf("%i", &PERSON.age); // age is `int` so & needed
fprintf(fp,"%s %i\n",PERSON.name, PERSON.age);
EDIT: Because you commented, your code is working after these rectifications, see
$ gcc x.c -Wall
$ ./a.out
Would you like to add a person to the list? [y/n]y
Enter a name:
yourname
14
Would you like to add a person to the list? [y/n]y
Enter a name:
firendName
15
Would you like to add a person to the list? [y/n]n
sh: 1: pause: not found
$ cat person_struct.txt
yourname 14
firendName 15

In addition to Grijesh's answer:
Please explain scanf("%s", &ans);. How many characters can you store in ans? How many characters does the string "y" require to store? Verify your beliefs: printf("sizeof ans: %zu\n" "sizeoof \"y\": %zu\n", sizeof ans, sizeof "y");
Perhaps you meant: if (scanf("%c", &ans) != 1) { /* assume stdin has closed or reached EOF */ }. Note the %c, which will read only one character into ans.
Alternatively, if you change ans to an int, you can use: ans = getchar();
edit: In short, I think your loop should look something like this:
for (size_t ppl = 0; ppl < 25; ppl++){
int ans;
printf("Would you like to add a person to the list? [y/n]");
do {
ans = getchar();
while (ans >= 0 && isspace(ans));
if (ans != 'y') {
break;
}
printf("Enter a name:\n");
if (scanf("%s", PERSON.name) != 1 || scanf("%i", &PERSON.age) != 1) {
break;
}
fprintf(fp, "%s %i\n", PERSON.name, PERSON.age);
}

Related

fprintf function in code writes garbage data into .csv file

I'm trying to create a C program which collect's an applicant's information. When a user is prompted to enter their written subjects, the program writes rubbish data into the .csv file when they wrote one. And sometimes does the same when the number of subjects written is two.
I've tried to clear the buffer stream, but it's no use. Strangely, using different compliers like DevC++, Embarcadero DevC and VS Code produces different results.
Edit: I've also noticed the chances of the rubbish values being written into the file are lowered when the grades of the subjects is lower than the number of subjects written.
Attached below is the code. And an image of the output.
// C libraries.
#include <stdio.h> // Contains function prototypes for the standard input/output library functions, and information used by them.
#include <conio.h> // Contains function prototypes for the console input/output library functions.
#include <stdlib.h> // Contains function prototypes for conversions of numbers to text and text to numbers, memory allocation, random numbers and other utility functions.
#include <string.h> // Contains function prototypes for string-processing functions.
#include <time.h> // Contains function prototypes and types for manipulating the time and date.
#include <stdbool.h> // Contains macros defining bool, true and false, used for boolean variables.
struct Applicant
{
int applicationID;
int dateOfApplication;
char lastName[21];
char firstName[21];
char middleName[21];
char dateOfBirth[21];
int age;
char gender;
char address[100];
char phoneNumber[21];
char emailAddress[51];
char mobileNumber[21];
int numSubjectsWritten;
char csecSubjects[20][100];
char grades[20];
char programmeSelection[10];
};
struct Applicant getApplicantData()
{
struct Applicant applicant;
int i = 0;
int numSubjects;
// Asking for applicant input for various fields.
printf("| Personal |");
printf("\nEnter Last Name: ");
scanf(" %20s", &applicant.lastName);
fflush(stdin);
printf("\nEnter First Name: ");
scanf(" %20s", &applicant.firstName);
fflush(stdin);
printf("\nEnter Middle Name (If you don't have a middle name, leave this field blank.): ");
gets(applicant.middleName);
fflush(stdin);
/*
printf("\nEnter Date of Birth: ");
scanf(" %s", &applicant.dateOfBirth);
fflush(stdin);
printf("\nEnter Gender. 'M' for male, 'F' for female, (M|F): ");
scanf(" %c", &applicant.gender);
fflush(stdin);
printf("\n\n| Contact Information |");
printf("\nEnter Address: ");
gets(applicant.address);
fflush(stdin);
printf("\nEnter Phone Number: ");
gets(applicant.phoneNumber);
fflush(stdin);
printf("\nEnter Email Address: ");
gets(applicant.emailAddress);
fflush(stdin);
printf("\nEnter Mobile Number: ");
gets(applicant.mobileNumber);
fflush(stdin);
*/
printf("\n\n| Education |");
printf("\nEnter Number of Subjects Written: ");
scanf("%d", &applicant.numSubjectsWritten);
fflush(stdin);
while (i < applicant.numSubjectsWritten)
{
printf("\nEnter the subject: ");
gets(applicant.csecSubjects[i]);
fflush(stdin);
printf("\nEnter the grade for that subject: ");
scanf(" %c", &applicant.grades[i]);
fflush(stdin);
i++;
}
return applicant;
}
int main(void)
{
FILE *file = fopen("Data.csv", "a+");
int i, j;
if (!file)
{
printf("\nError! Can not open data file.\nPlease contact the Program Addmission Manager as soon as possible with the error message.");
exit(1);
}
else
{
struct Applicant applicant = getApplicantData();
//fprintf(file, "%s:%s:%s:%s:%c:%s:%s:%s:%s", applicant.lastName, applicant.firstName, applicant.middleName, applicant.dateOfBirth, applicant.gender, applicant.address, applicant.phoneNumber, applicant.emailAddress, applicant.mobileNumber);
fprintf(file, "%s:%s:%s:", applicant.lastName, applicant.firstName, applicant.middleName);
for (i = 0; applicant.csecSubjects[i][0] != '\0'; i++)
{
fprintf(file, " %s", applicant.csecSubjects[i]);
fflush(stdout);
fflush(stdin);
fflush(file);
fprintf(file, " ( %c):", applicant.grades[i]);
fflush(stdout);
fflush(stdin);
fflush(file);
}
}
return 0;
}
First problems I see:
Remove the & from all instances where you scanf a string
Don't use gets, or mix scanf and fgets
Don't fflush(stdin)
Instead of scanf, consider using a custom-made input method with condition checking and anything you need. I will give an example.
#define BUFFER_SIZE 512
void input(char* buffer){
memset(buffer, 0, BUFFER_SIZE); // Initializing the buffer.
fgets(buffer, BUFFER_SIZE, stdin);
strtok(buffer,"\n");
}
How to take input using that?
void main(){
int username[BUFFER_SIZE];
input(username);
}
A way to write a structure to a file is shown below.
void Structure_Print(Applicant* applicant, FILE* stream, int no_of_applicant){
if(no_of_applicant==0){
fprintf(stdout, "No applicant yet.\n");
return;
}
fprintf(stream, "%s:%s:%s:", applicant.lastName, applicant.firstName, applicant.middleName);
for (i = 0; applicant.csecSubjects[i][0] != '\0'; i++)
{
fprintf(stream, " %s:", applicant.csecSubjects[i]);
fprintf(stream, " %c:", applicant.grades[i]);
}
return;
}
Also, I noticed how you tried to make it readable while saving it in subject(grade) format. I recommend you to not do that. Your .csv file is just for database. Nobody is going to read it. So just store the data by comma or any character separator. It will make it easier to extract data later.

using fgets with structure

I am trying to use fgets with structure, since I have to insert in character array. But when I use fgets it's not working properly. I can not enter value for the char array. Please help. Below is a sample program::
#include <stdio.h>
#include<string.h>
struct Student
{
int roll;
char name[50];
int age;
char branch[50];
char gender[1]; //F for female and M for male
};
int main()
{
struct Student s1;
printf("enter roll number of the student: ");
scanf("%d", &s1.roll);
printf("Enter student name: ");
fgets(s1.name, 50, stdin); // NOT WORKING ...
printf("Enter age number: ");
scanf("%d", &s1.age);
printf("Enter branch number: ");
scanf("%d", &s1.branch);
printf("Enter Gender: ");
scanf("%d", &s1.gender);
return 0;
}
First of all you need different format specifiers for different datatypes. So you need to use %c for a character and %[^\n] for a string containing spaces.
You also need to remove leading whitespaces before scanning a string, because a newline \n is left in the input buffer which would otherwise be read by %c and %[], as Weather Vane pointed out in a comment.
#include <stdio.h>
#include <string.h>
struct student
{
int roll;
char name[50];
int age;
char branch[50];
char gender; // can be a single character
};
int main(void)
{
struct student s1;
printf("Enter roll number: ");
scanf("%d", &s1.roll);
printf("Enter name: ");
scanf(" %49[^\n]", s1.name); // use %[^\n] to scan a string containing spaces
printf("Enter age: ");
scanf("%d", &s1.age);
printf("Enter branch name: ");
scanf(" %49[^\n]", s1.branch);
printf("Enter gender: ");
scanf(" %c", &s1.gender); // %c is the format specifier for a char
return 0;
}
fgets is not being bypassed, it's actually working as it should, what happens is that it reads the newline character that remains in the input buffer from the previous scanf, if you access s1.name you will see that it has a string ("\n\0") in it.
For name I have to insert space character too, so I used fgets
You can use scanf with [^\n] specifier which can read spaces. Mixing scanf with fgets is trouble, it can be done, but you should avoid it.
You should either use scanf only, or fgets only, in the latter case, if you need to convert strings to ints use sscanf or better yet strtol.
Your code has other issues, detailed in the comments with corrections:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Student
{
int roll;
char name[50];
int age;
char branch[50];
char gender; //F for female and M for male
};
For solution with scanf only it should, more or less, look like this:
void clear_buffer(){ // helper function to clear buffer
int c;
while((c = getchar()) != '\n' && c != EOF){}
if(c == EOF){
fprintf(stderr, "Fatal error!");
exit(EXIT_FAILURE);
}
}
int main()
{
struct Student s1;
printf("enter roll number of the student: ");
while (scanf("%d", &s1.roll) != 1){
fprintf(stderr, "Bad input, try again: ");
clear_buffer();
} // if bad input ask again
printf("Enter student name: "); // the space before % clears blanks
while (scanf(" %49[^\n]", s1.name) != 1){ // will read the line until
fprintf(stderr, "Bad input, try again: "); // enter is pressed, provided
clear_buffer(); // that it's not larger than 49
}
printf("Enter age number: ");
while(scanf("%d", &s1.age) != 1){
fprintf(stderr, "Bad input, try again: ");
clear_buffer();
}
printf("Enter branch number: ");
while (scanf(" %49[^\n]", s1.branch) != 1){ // branch is a string, %d
clear_buffer(); // specifier is for ints.
fprintf(stderr, "Bad input, try again: "); // note that I'm using width
} // limit (49) to avoid buffer overflow
printf("Enter Gender: ");
while(scanf(" %c", &s1.gender) != 1){ // only 1 character needed, use %c
fprintf(stderr, "Bad input, try again: ");
clear_buffer();
}
}
For a solution with fgets only which, I would argue is better, you can do something like this:
int main(){
struct Student s1;
char temp[50];
printf("enter roll number of the student: ");
if (fgets(temp, sizeof temp, stdin)){
if (sscanf(temp, "%d", &s1.roll) != 1){
fprintf(stderr, "Error parsing input!\n");
}
}
printf("Enter student name: ");
if (fgets(temp, sizeof temp, stdin)){
if (sscanf(temp, "%49[^\n]", s1.name) != 1){
fprintf(stderr, "Error parsing input!\n");
}
}
printf("Enter age number: ");
if (fgets(temp, sizeof temp, stdin)){
if (sscanf(temp, "%d", &s1.age) != 1){
fprintf(stderr, "Error parsing input!\n");
}
}
printf("Enter branch number: ");
if (fgets(temp, sizeof temp, stdin)){
if (sscanf(temp, "%49[^\n]", s1.branch) != 1){
fprintf(stderr, "Error parsing input!\n");
}
}
printf("Enter Gender: ");
if (fgets(temp, sizeof temp, stdin)){
if (sscanf(temp, " %c", &s1.gender) != 1){
fprintf(stderr, "Error parsing input!\n");
}
}
}
*scanf to parse ints still has a potencial flaw in case of overflow, there is no way of guarding against that, unless you use a more robust method like the aforementioned strtol.

Restrict User To Enter Integers?

Hello I Want To Ask A Question About That How i Restrict User From Enter Integers And Enter Only String OR Characters.
If You Know The Answer Can You Fit That In My Code Below that Would be great if you do that btw forget the date part its just other thing.
void checkin()
{
char comp_choice,more_choice,in_comp_choice;
int comp_amount;
int date_month[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int date_month1[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int charges_per_room_per_day = 5000,bill;
struct info user;
system("cls");
printf("\t\tCHECK IN FORM\n");
printf("Please Fill Following Information\n");
FILE *fp;
fp = fopen("checkin.txt","a");
time_t t;
time(&t);
printf("First Name : ");
fflush(stdin);
gets(user.first_name);
printf("Last Name : ");
fflush(stdin);
gets(user.last_name);
fflush(stdin);
printf("Contact Number : ");
gets(user.contact_no);
fflush(stdin);
printf("\nGuests : ");
scanf("%d",&user.guest);
printf("Rooms : ");
scanf("%d",&user.rooms);
fprintf(fp,"%s %s %s %d %d\n",user.first_name,user.last_name,user.contact_no,user.guest,user.rooms);
Label2:
printf("Today date and time is %s\n",ctime(&t));
printf("Check In date (DD-MM-YYYY) : ");
scanf("%d %d %d",&user.date,&user.month,&user.year);
printf("Check out date (DD-MM-YYYY) : ");
scanf("%d %d %d",&user.date1,&user.month1,&user.year1);
This Is Image of i am entering Integers And Program Doesn't Say Any Thing
A way to enforce a user entering a valid integer is to read in whatever the user enters (e.g. into a char[..]-buffer), and then to interpret/check the result as required. For this check, you can then either write your custom logic, or use the logic of built in functions, like, for example, strol.
The following sample makes use of strtol. The signature of strtol is long int strtol(const char *nptr, char **endptr, int base). Basically, after a successful scan, endptr will point to the first character of nptr after the (successfully) scanned number; if we do not accept any characters after a (valid) number, we check if endptr actually points to string terminator '\0'; in the case of an unsuccessful scan, endptr is equal to nptr.
Here you go:
#include <stdio.h>
#include <stdlib.h>
int enterIntegerValue(const char *message) {
char inputBuffer[21];
char *endOfScan;
bool error;
int result;
do {
printf("%s", message);
scanf("%20s", inputBuffer);
result = (int)strtol(inputBuffer,&endOfScan,10);
error = (endOfScan == inputBuffer) || (*endOfScan != '\0');
if (error)
printf("Invalid number. Please enter a valid integer number.");
}
while (error);
return result;
}
int main()
{
int rooms = enterIntegerValue("Rooms : ");
printf("input: %d", rooms);
return 0;
}

scanf("%[^\n]") gets skipped

I want to write a little program to learn C; here it is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int total;
char suffix[3];
struct person {
char id[11];
char name[21];
char sex[7];
int age;
char phone[12];
};
char* number_suffix (int number) {
int mod;
mod = number % 10;
switch (mod) {
case 1:
strcpy(suffix, "st");
break;
case 2:
strcpy(suffix, "nd");
break;
case 3:
strcpy(suffix, "rd");
break;
default:
strcpy(suffix, "th");
break;
}
return suffix;
}
void input_info (struct person info[], int total_people) {
int counter;
for (counter=0; counter<total_people; counter++){
printf("%s%d%s%s\n","Please input the ID(10 digits) of ", (counter+1),
number_suffix(counter), " person: ");
scanf("%s", info[counter].id);
fflush(stdin);
printf("%s%d%s%s\n", "Please input the Name(20 chars) of ", (counter+1),
number_suffix(counter), " person: ");
scanf("%[^\n]", info[counter].name);
fflush(stdin);
printf("%s%d%s%s\n", "Please input the Sex(Male/Female) of ", (counter+1),
number_suffix(counter), " person: ");
scanf("%s", info[counter].sex);
fflush(stdin);
printf("%s%d%s%s\n", "Please input the Age(1~100) of ", (counter+1),
number_suffix(counter), " person: ");
scanf("%d", &info[counter].age);
fflush(stdin);
printf("%s%d%s%s\n", "Please input the Phone of ", (counter+1),
number_suffix(counter), " person: ");
scanf("%s", info[counter].phone);
fflush(stdin);
}
printf("%s\n%s\n%s\n%d\n%s\n", info[counter].id, info[counter].name, info[counter].sex, &info[counter].age, info[counter].phone);
}
int main (void) {
printf("%s\n", "Please input a number that how many people you want to record:");
scanf("%d", &total);
fflush(stdin);
struct person *person_info = malloc(sizeof(struct person)*total);
input_info(person_info, total);
free(person_info);
return 0;
}
I found something weird, when I run it.
Please input a number that how many people you want to record:
1
Please input the ID(10 digits) of 1th person:
A01
Please input the Name(20 chars) of 1th person:
Please input the Sex(Male/Female) of 1th person:
Male
Please input the Age(1~100) of 1th person:
32
Please input the Phone of 1th person:
1224464
[empty line]
[empty line]
[empty line]
1926234464
[empty line]
Is that program skip scanf("%[^\n]", info[counter].name); this line when it run?
Why, and what causes it?
fflush(stdin) is undefined as per the C standard, but it works on some implementations. But it is best to avoid it as it isn't portable and may invoke Undefined Behavior.
To fix the issue, replace all fflush(stdin)s with
int c; /* Declare it once */
while((c = getchar()) != '\n' && c != EOF); /* Discards everything until a newline character or EOF */
Another problem is with
printf("%s\n%s\n%s\n%d\n%s\n", info[counter].id, info[counter].name, info[counter].sex, &info[counter].age, info[counter].phone);
It should be
printf("%s\n%s\n%s\n%d\n%s\n", info[counter].id, info[counter].name, info[counter].sex, info[counter].age, info[counter].phone);
and should be placed inside the for loop. Otherwise, you invoke Undefined Behavior because
You passed an int* for %d which expects an int.
You access invalid memory location beyond the allocated memory segment.
Also, as others have said, pass counter + 1 to number_suffix.
Problem is with your scanf pattern. Use " %[^\n]" instead of "%[^\n]" to not catch \n (After previous data entry)
Pass counter + 1 to number_suffix
How to understand the relation between pointers, struct, malloc, functions parameters?
Read Understanding and Using C Pointers from O'Reilly Media

fprintf in do while loop wrote only one line in file C

I don't know why it is writing only one line in my file
void foo()
{
int ID;
char answer;
FILE *input = fopen("Dane.txt", "w");
do
{
printf("Give ID: ");
scanf("%d",&ID);
fprintf(input, "%d\n", ID);
printf("Exit? y/n ");
scanf("%s", &answer);
fflush(NULL);
}
while (answer != 'n');
fclose(input);
}
Output (in file) is only first ID number which I write on console. But where are others?
EDIT: ok I got it. The error was in char answerand it should be char answer[2] and ending while should be while(answer[0] != ...). Before it the program read only one character - the line end. When i hit e.g. "n ENTER" it take only ENTER. Now it take the first char from tab i.e. "n". Thank everybody for help
You are doing some logical mistake. You are asking whether exit or not. If user does not want to exit, then he would press n. So, to continue the loop, the answer should be equal to n, right?
Modified version of your program:
void foo()
{
int ID;
char answer;
FILE *input = fopen("Dane.txt", "w");
do
{
printf("Give ID: ");
scanf("%d",&ID);
fprintf(input, "%d\n", ID);
printf("Exit? y/n ");
scanf(" %c", &answer);
fflush(NULL);
}
while (answer == 'n');
fclose(input);
}
answer has only one space to read and it isn't capable to store string whose length is 1 character or longer.
This won't affect the result, but using input for output file pointer is confusing.
The conditio in while is unnatural.
Try this:
#include <stdio.h>
void foo();
int main() {foo(); return 0;}
void foo()
{
int ID;
char answer[4];
FILE *output = fopen("Dane.txt", "w");
if (output == NULL) return;
do
{
printf("Give ID: ");
if (scanf("%d",&ID) != 1) break;
fprintf(output, "%d\n", ID);
printf("Exit? y/n ");
if (scanf("%3s", answer) != 1) break;
fflush(NULL);
}
while (answer[0] != 'y');
fclose(output);
}
When I ran your function, I got all three numbers I entered in the file:
$ ./a.out
Give ID: 25
Exit? y/n y
Give ID: 33
Exit? y/n y
Give ID: 10
Exit? y/n n
$ cat Dane.txt
25
33
10
However, your question is backwards. You ask, "Exit? y/n" and then exit if the answer is "n" ("no"). The question should be "Continue? y/n", so that when the user answers in the affirmative, it continues.
Also, naming your output filehandle "input" is backwards, and as others have mentioned, your answer variable should be a character array of at least 2 characters, as char answer[2];.

Resources