Printf function does not works with char - c

I got a problem, because the printf fuction does not show any result when I try to debug the code. What I am doing wrong? Can someone tell me? I tried to put the buffor, to make a space before the %s in scanf, but it does not work.
struct worker {
char name[50];
};
struct worker tab[1000];
int worker_count=0;
int c = getchar();
if (c == 'D') {
++worker_count;
printf("Put the name:");
fflush(stdin);
scanf_s(" %s", &tab[worker_count].name, 1);
printf("Imie: %s\n",tab[worker_count].name);
}
system("pause");

Related

C structures displaying numbers rather than user data

Kindly help me debug this code. It is not displaying the correct data. The following program is supposed to get book details from the user, dynamically allocate memory to them and display them.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "problem5.h"
int main()
{
struct books *b;
b = (struct books*)malloc(sizeof(struct books));
int command, flag = 0;
int n=0, i;
while(flag == 0)
{
printf ("1. Add Book\n");
printf ("2. View Books\n");
printf ("3. Quit\n");
scanf("%d", &command);
if (command == 1)
{
printf ("Enter Name\n");
//scanf("%d", &(b+i)->name);
scanf(" ");
gets((b+i)->name);
printf ("Enter Author\n");
//scanf("%d", &(b+i)->author);
scanf(" ");
gets((b+i)->author);
printf ("Enter Year Published\n");
scanf("%d", &(b+i)->year_published);
n=n+1;
i=n;
} else if (command == 2)
{
for(i=0; i<n; i++)
{
printf ("%d - %d by %d\n", (b+i)->year_published, (b+i)->name, (b+i)->author);
}
} else if (command == 3)
{
flag = 1;
} else
{
printf ("Invalid choice!\n");
}
}
}
The following is problem5.h header file that has the structure books. Initially I didn't declare the variables in array since I didn't want to use much memory. But I had to due to many errors.
#define PROBLEM3_H_INCLUDED
typedef struct books{
char *name[30];
char *author[30];
int year_published;
};
#endif // PROBLEM3_H_INCLUDED
When I print I am getting random numbers instead of the data the user entered.
The overall design of your code is wrong.
This is basically what you want.
I made following changements:
using meaningful variable names
changed struct book so the structure can contain one book. Also renamed it from struct books to struct book because the structure contains only one book.
allocating memory properly
using books[numberofbooks].x instead of the less readable *(books + numberofbooks)->x
More explanations in the comments.
#include <stdio.h>
#include <stdlib.h>
struct book {
char name[30];
char author[30];
int year_published;
};
int main()
{
struct book* books = NULL; // no books at all initially so we
// initialize to NULL
// so we can simply use realloc
int numberofbooks = 0;
int programend = 0;
while (programend == 0)
{
printf("1. Add Book\n");
printf("2. View Books\n");
printf("3. Quit\n");
int command;
scanf("%d", &command);
if (command == 1)
{
getchar(); // consume Enter key (due su scanf)
// allocate memory for one more book
books = realloc(books, sizeof(struct book) * (numberofbooks + 1));
printf("Enter Name\n");
gets(books[numberofbooks].name);
printf("Enter Author\n");
gets(books[numberofbooks].author);
printf("Enter Year Published\n");
scanf("%d", &books[numberofbooks].year_published);
numberofbooks++; // increment number of books
}
else if (command == 2)
{
for (int i = 0; i < numberofbooks; i++)
{
printf("%d - %s by %s\n", books[i].year_published, books[i].name, books[i].author);
}
}
else if (command == 3)
{
programend = 1;
}
else
{
printf("Invalid choice!\n");
}
}
}
There is still room for improvement though:
error checking for realloc
error checking for interactive I/O
not using the deprecated and dangerous gets
and certainly a few other things
b = (struct books*)malloc(sizeof(struct books));
Here, you are allocating memory for only one instance of struct books , But you are accessing multiple instances of struct books.
printf ("%d - %d by %d\n", (b+i)->year_published, (b+i)->name, (b+i)->author);
For i>=1 (b+i) is not defined, because you did not allocate memory for it. You have allocated memory for only (b+0).
int n=0, i;
gets((b+i)->name);
Here, i has not been initiliazed.

Problem with the structures and loops in c programming

I wanted to create a program in c that reads the student name, roll number, marks of 3 subjects. when I run the program it is showing no errors, but the problem is whenever I try to input information it is taking only 2 inputs. Anyone please check the program and state the error in my program.
#include <stdio.h>
struct student
{
char sname[20];
int srollno;
int smarks[3];
};
int main ()
{
struct student e[3];
int i,j;
for (i=0;i<=2;i++)
{
scanf ("%s",e[i].sname);
scanf ("%d",e[i].srollno);
for (j=0;j<=2;j++)
{
scanf ("%d",e[i].smarks[j]);
}
}
}
it is taking only two inputs.
you have some problem in your scanf.
Try this:
scanf("%s",&e[i].sname);
I perform some little change on your code.
This is working version of code.
Code
#include <stdio.h>
struct student
{
char sname[20];
int srollno;
int smarks[3];
};
int main ()
{
struct student e[3];
int i,j;
for (i=0;i<=2;i++)
{
printf("Name: ");
scanf("%s", e[i].sname);
printf("roolNumber: ");
scanf("%d", &e[i].srollno);
for (j=0;j<=2;j++)
{
printf("Mark %d: ",j);
scanf("%d", &e[i].smarks[j]);
}
}
printf("\n\nprinting \n\n");
for (i=0;i<=2;i++)
{
printf("Name: %s\n", e[i].sname);
printf("roolNumber: %d\n", e[i].srollno);
for (j=0;j<=2;j++)
{
printf("Mark: %d\n", e[i].smarks[j]);
}
printf("\n");
}
}
Compile and Run
gcc -Wall source.c -o source
./source
I suggest to use printf() before try to scanf(), this makes User Interface better.
scanf() char array don't need & (address) operator. see this
char str[10];
scanf("%s", str);
printf("%s\n", str);
Work exactly like
char str[10];
scanf("%s", &str[0]);
printf("%s\n", str);
Because str is pointer to its first elementstr[0]. As stated in link we can write printf("%d\n", str==&str[0]); and always the result is one that show str and &str[0] are identical.

C Program error with char

When I execute the program it asks me for my name if I put more than one letter it has an error and it shuts down and in the second one anyting I put it fails and closes instantly
#include <stdio.h>
int main () {
char firstname[20];
char lastname[20];
char response[20];
printf ("Type your first name:\n");
scanf ("'c'",&firstname);
printf ("\n");
printf ("Type your last name:\n");
scanf ("'c'",&lastname);
printf ("\n");
printf ("Hi %s %s do you want to stop giving me information?\nSay Y or N");
scanf ("%s",&response);
if (response == 'Y' || response == 'y'); {
system ("pause<NULL");
}
printf("Thank you for using my program. Good Bye!\n\n");
system ("pause<NULL");
}
There are many issues:
You probably want this (untested code)
#include <stdio.h>
int main () {
char firstname[20];
char lastname[20];
char response[20];
printf ("Type your first name:\n");
scanf ("%s", firstname);
printf ("\n");
printf ("Type your last name:\n");
scanf ("%s", lastname);
printf ("\n");
printf ("Hi %s %s do you want to stop giving me information?\nSay Y or N", firstname, lastname);
scanf ("%s",response);
if (response[0] == 'Y' || response[0] == 'y') {
system ("pause<NULL");
}
printf("Thank you for using my program. Good Bye!\n\n");
system ("pause<NULL");
return 0;
}
There is no 'c' format specifier, it's %s
scanf ("%s", &firstname) is wrong, firstname is already the address of the buffer
response == 'y'is wrong, response is the address of the buffer, you just need the first char of the buffer, that is responde[0]
if (response[0] == 'Y' || response[0] == 'y'); {, there was a stray ; before the {
Your problem is that you are asking for a char input, you want a string.
tutorialspoint has a simlpe and claean example.
https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm

Continue taking input in while loop in c. I've tried fflush

I'm learning data structures in C and I need to take input from the user. I learned from searching other stackoverflow questions that I need to use fflush after I print something.
The issue I'm having is when I type add it doesn't print anything until I break the while loop by entering quit twice. Can someone explain how to fix this and why it happens please?
Here's the code:
#include "stdio.h"
typedef struct S_RacingCar {
char name[8];
int speed;
} RacingCar;
const int MaxCars = 4;
void PrintList() {
printf("List Print...\n");
}
int AddCar(RacingCar *car) {
printf("Enter Name And Speed:\n\n");
char input[16];
fgets( input, 15, stdin);
int ok = 0;
int result = sscanf(input, "%s %d", car->name, car->speed);
if (result == 2) {
ok = 1;
printf("Added:%s Speed:%d\n\n", car->name, car->speed);
fflush(stdout);
} else {
printf("Sorry, error parsing input\n\n");
}
return ok;
}
int main() {
RacingCar allCars[MaxCars];
int numCars = 0;
char command[16];
char input[16];
while( fgets(input, 15, stdin) ){
sscanf(input,"%s",command);
if ( strncmp(command, "quit", 4) == 0){
printf("\n\nBreaking...\n");
break;
} else if ( strncmp(command, "print", 5) == 0){
PrintList();
fflush(stdout);
} else if ( strncmp(command, "add", 3) == 0){
if (numCars < MaxCars) {
numCars += AddCar( &allCars[numCars] );
fflush(stdout);
} else {
printf("Sorry List is Full!!\n\n");
}
}
fflush(stdout);
}
return 0;
}
The output I get after I type print, and then add is:
print
List Print...
add
The cursor is left blinking under add. If I enter quit I get:
print
List Print...
add
quit
Enter Name And Speed:
Sorry, error parsing input
So the program hasn't ended and I'm wondering why. Could someone explain?
To end the program I have to enter quit again:
print
List Print...
add
quit
Enter Name And Speed:
Sorry, error parsing input
quit
Breaking...
<<< Process finished. (Exit code 0)
================ READY ================
The reason that your program behaves weirdly is because it exhibits UB.
Change
int result = sscanf(input, "%s %d", car->name, car->speed);
To
int result = sscanf(input, "%s %d", car->name, &(car->speed));
This is done because sscanf expects an int* but you give it an int.
Also, you can add
setvbuf(stdout, NULL, _IONBF, 0);
at the start of main and remove all the fflush() in your program. The above line flushes the stdout whenever it is written to.
In addition to the other answer, change:
int AddCar(RacingCar *car) {
printf("Enter Name And Speed:\n\n");
to:
int AddCar(RacingCar *car) {
fflush(stdout);
printf("Enter Name And Speed:\n\n");

User Input to File

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

Resources