How to use char in scanf by using loop? - c

I want to make simple billing software but I don't know to fix this problem
#include <stdio.h>
int main()
{
char a[20];
int i, j, b;
i = 0;
printf("How many item you have?\n>>> ");
scanf("%d", &j);
for (int i = 0; i < j; i++)
{
printf("Type the name of item no. %d?\n>>> ", i + 1);
scanf("%c", &a);
printf("Type the item quantity?\n>>> ");
scanf("%d", &b);
}
return 0;
}
This code is only for asking questions, as you can see. In this code everything is fine but, when I run this code, the output is:
How many item you have?
>>> 4
Type the name of item no. 1?
>>> Type the item quantity?
>>>
Everything seems fine but I haven't entered the item name and the loop is asking the 2nd question directly. How is it even possible?

The %c format specifier for scanf reads a single character. To read a string (array) of characters, use the %s format specifier. Also, for such arrays, you don't need the & (address of) operator, as the array name itself will 'decay' to a pointer to its first element:
#include <stdio.h>
int main()
{
char a[20];
int i, j, b;
i = 0;
printf("How many item you have?\n>>> ");
scanf("%d", &j);
for (int i = 0; i < j; i++) {
printf("Type the name of item no. %d?\n>>> ", i + 1);
scanf("%19s", a); // The "19" limits input size and allows space for the nul-terminator
printf("Type the item quantity?\n>>> ");
scanf("%d", &b);
}
return 0;
}

Related

Code to print data of a name, price and its pages by using arrays

#include<stdio.h>
int main(){
char name[3];
float price[3];
int i,page[3];
printf("enter the name price and book\n");
for(i=0;i<3;i++){
scanf("%s",name[i]);
printf("enter character:\n");
}
for(i=0;i<3;i++) {
scanf("%f",&price[i]);
printf("enter floating point number:\n");
}
for(i=0;i<3;i++) {
scanf("%d",&page[i]);
printf("enter digit:\n");
}
printf("\n");
for(i=0;i<3;i++) {
printf("%s\n",name[i]);
}
for(i=0;i<3;i++) {
printf("%f\n",&price[3]);
}
for(i=0;i<3;i++){
printf("%d\n",&page[i]);
}
return 0;
}
When I was trying this code, I thought this was quite simple to do but I realized, there is something which I am missing in the code. The main problem with this code is it is not scanning the values of price and pages. I don't understand where I am mistaken.
So, please correct my code so that it will print the values of name price and pages.
There are a number of issues in your code. First and foremost, the %s specifier (for both the scanf and printf functions) expects a string argument (that is, a nul-terminated array of char for printf or an array sufficiently large to hold the input characters plus that terminator, for scanf); however, you are attempting to read (and print) a single char value in each of the relevant for loops.
To fix this, use the %c format specifier, instead of %s. However, when you use this, the newline character that is generated when you press the Enter key will be left in the input buffer, and that will be read as the actual char input on the next iteration of the first for loop. To clear any such newline (or, indeed other whitespace) from the input before the real input, add a space in the format string before the %c. Also, when using this, you will need to pass the address of each name element: scanf(" %c", &name[i]);.
Further, the printf function takes the actual values of the variables to be output, rather than their addresses – so remove the & from the arguments in your printf calls. (Also, and I assume it's a typo, the price[3] expression should be price[i] – the former attempts to access an out-of-bounds element of the price array.)
Another issue is that, in each of your input loops, you call the scanf function before you display the relevant prompt. In the code below, I have reversed your printf and scanf lines in each of those input loops.
Here's a possible fixed version:
#include<stdio.h>
int main()
{
char name[3];
float price[3];
int i, page[3];
printf("enter the name price and book\n");
for (i = 0; i < 3; i++) {
printf("enter character:\n");
scanf(" %c", &name[i]);
}
for (i = 0; i < 3; i++) {
printf("enter floating point number:\n");
scanf("%f", &price[i]);
}
for (i = 0; i < 3; i++) {
printf("enter digit:\n");
scanf("%d", &page[i]);
}
printf("\n");
for (i = 0; i < 3; i++) {
printf("%c\n", name[i]);
}
for (i = 0; i < 3; i++) {
printf("%f\n", price[i]);
}
for (i = 0; i < 3; i++) {
printf("%d\n", page[i]);
}
return 0;
}

How do I get input for an array from a user in C programming?

I am new to C and I've run into a bit of a problem when it comes to user input for an array.
Here is the code
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n, i;
int score [n];
printf("Number of scores: ");
scanf("%d", &n);
for(i=0; i<n; i++){
printf("score: ");
scanf("%d", &score[i]);
}
return 0;
}
It does not matter what value I set for n. It always prompts the user 4 times.
As mentioned in comments, you must change this:
/* bad */
int score [n];
printf("Number of scores: ");
scanf("%d", &n);
into this
/* good */
printf("Number of scores: ");
scanf("%d", &n);
int score [n];
This since C executes code from top to bottom like when you are reading a book. It will not "double back" a few rows above and fill in n once it has been entered by the user. At the point where you declare int score [n], n must already be known.
If your using an array with unknown size during compilation, I would suggest using memory allocation. So the user determines the array size while running the program.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n, i;
int *score;
printf("Number of scores: ");
scanf("%d", &n);
score = (int *)malloc(sizeof(int)*n);
for(i=0; i<n; i++){
printf("score: ");
scanf("%d", &score[i]);
}
free(score)
return 0;
}
The malloc function allocates memory with the size of n and returns a pointer to the allocated memory.

Having problems with 2D char arrays

So I've got an assignment where my program asks the brand (10 letters), model (10 letters), age (1986 - 2019) and cost (positive real number) of 10 cars and then wants the program to check which car is the oldest and to print out it's brand and model. I don't have a problem with the first part but with the second part.
The code is:
//First part
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define C 10
#define M 11
int main(void)
{
char brand[C][M];
char model[C][M];
int year[C];
float cost[C];
int i, len1, len2, min;
for(i=0; i<C; i++){
printf("Car %d\n", i+1);
do{
printf("Brand: ");
scanf("%s", brand[i]);
len1 = strlen(brand[i]);
} while(len1<0 || len1>10);
do{
printf("Model: ");
scanf("%s", model[i]);
len2 = strlen(model[i]);
} while(len2<0 || len2>10);
do{
printf("Year: ");
scanf("%d", &year[i]);
} while(year[i]<1986 || year[i]>2019);
do{
printf("Cost: ");
scanf("%d", &cost[i]);
} while(cost[i]<=0);
}
//Second part
year[0] = min;
for(i=0; i<10; i++)
if(year[i] < min){
min = year[i];
printf("\nThe oldest car is %s %s\n", brand[i], model[i]);
}
For some reason it either prints out gibberish in the place of brand[i] or if I lose the columns of the if statement prints out all the car brands and their models, where I only want the oldest one.
Aside from scanf not being recommended there are some problems with this code, first when you read the brand and model you do:
do{
printf("Brand: ");
scanf("%s", brand[i]);
len1 = strlen(brand[i]);
} while(len1<0 || len1>10);
The problem here is that you first write the string to brand[i] and then check if it's too long, but you have already written it into the array so if the string is longer than your space you already have a buffer overflow. Limit the size you can read with scanf using scanf("%10s, brand[i]) or better yet use fgets(brand[i], sizeof(brand[i]), stdin).
Next in the second part you use min without initializing it, and you overwrite the content of year[0] with it. You probably wanted something like:
min = 2020; // or a number that will be bigger than all your cars anyway
int older = 0;
i = 0;
for(i=0; i<C; i++){ // Use C here, you have it might as well use it instead of magic numbers
if(year[i] < min){
older = i;
min = year[i];
}
}
printf("\nThe oldest car is %s %s\n", brand[older], model[older]);
but bare in mind that this solution will print multiple cars if they are the oldest ones and have the same year

C: Array of Structs (Input into int array within array of structs)

Hi I have to create a database that stores students number, name and also stores an array of course marks (1-N) in C Programming Language.
Everything worked until I started coding for the array of course marks. Then every time I compiled the code it kept crashing as soon as it asked to input the course marks.
Can you please tell me where I'm going wrong in my programming for this task? I have attached it to this message.
The program worked for inputting the name, student number, however I could not get the program to input array of marks. I have asked how many course marks to be entered and then used a for loop within the "void insert(void)" function to keep inputting the course marks into the array *marks. I am referring specifically to lines 24 to 30 in my programming code.
Always at this point the program kept crashing and I could not proceed further to enter more names or print the stored student details.
I think there is a problem with this part:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n");
scanf("%d", &(list[num_students].marks[num_marks]));
}
Anyway here is the full code:
#include <stdio.h>
#include <string.h>
struct student{
int number;
char name[10];
int marks[5];
};
struct student list[10];
int num_students = 0;
int num_marks = 0;
int *p;
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++; // HOW DO WE INPUT ARRAY MARKS??? MARK1: , MARK2: , MARK3 ,
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
int main(void)
{
int code;
int opt1;
int courses, i, k, j, counter;
for (;;){
printf("Enter operation code: \n");
printf("(1) ADD NEW STUDENT DETAILS: \n");
printf("(2) DISPLAY REPORT OF ALL STUDENTS: \n");
scanf(" %d", &code);
switch (code){
case 1 :
insert();
break;
case 2 :
printtest();
break;
default:
printf("Illegal code\n");
printf("\n");
}
}
}
Apart from what others pointed out, I'd like to draw your attention towards the following:
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++;
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
There are three problematic statements:
scanf("%s", &list[num_students].name); This is why beginners should use compilers with all warnings enabled.
printf("Mark: %d /100 \n", list[i].marks); What did you declare marks as in the first place?
scanf("%d", num_marks); Seems like you put & operator where not needed and ignore where needed. Read your textbook before asking a question next time.
Seems like you're having a tough time understanding the concept of arrays and pointers. Read your text book thoroughly before venturing into the world of pointers. If you don't use them correctly, even compiler can't help you.
Also, even if I don't expect your program to have a robust input mechanism, at least array bounds checking is expected. Learn good habits from the beginning. They'll save a lot of your time while debugging later.
Seems to be an error in:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
The crash is probably because num_marks as index indexes beyond the array. Change to:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[i]));
}

Print the nth member among five members’ height using Structure

#include <stdio.h>
struct member {
char name[20];
int age;
char sex;
int height;
};
int main(void)
{
int i,j;
struct member input[5]={0,};
int tot, rank, max=0;
int max2[5]={0,};
float res;
for (i=0; i<5; i++)
{
scanf("%s ", input[i].name);
scanf("%d %c %d", &input[i].age, &input[i].sex, &input[i].height);
getchar();
}
scanf("%d", &rank);
max =input[0].height;
for(i=1;i<=5;i++) {
for(j=0;j<5;j++) {
if(max>=input[j].height)
max=max;
else
max=input[j].height;
}
max2[i]=max;
for(j=0;j<5;j++) {
if(max==input[j].height)
input[j].height*=(-1);
}
max=-1;
}
for (i=0; i<5; i++)
{
if(max2[rank]== input[i].height)
printf("%s %d %c %d\n",input[i].name, input[i].age, input[i].sex,input[i].height);
}
fflush(stdin);
getchar();
return 0;
}
The result printed of above my code is nothing...Even the height inputted becomes negative number..
What's wrong with this program?
Input & Print should be the same like example image.......
please help!
The first scanf should be fixed
scanf("%s ", input[i].name);
In the second scanf, the input[i].sex is a char type so you have to use "%c" instead of %s
scanf("%d %s %d", &input[i].age, &input[i].sex, &input[i].height);
should be
scanf("%d %c %d", &input[i].age, &input[i].sex, &input[i].height);
You have a lot of problems here:
1) You're taking the wrong parameters from scanf():
scanf("%s ", input[i].name); // You don't need a & for a string
scanf("%d %c %d", &input[i].age, &input[i].sex, &input[i].height); // you need %c for a
// character
2) You're using for(i=1;i<=5;i++) to access an array of 5 elements, by doing this you're overflowing the array (it should be 0 to 4, not 1 to 5)
3) This is a nit-pick but:
if(max>=input[j].height)
max=max;
that is totally pointless. You don't need to set a variable to itself, just invert the logic (<) and only do the else case.
4) You set all the input[x].height's to the negative of the value they're originally set to here:
input[j].height*=(-1);
Then you check to see if that is the same as the original values which you stored in max2[] before printing here:
if(max2[rank]== input[i].height)
printf("%s %d %s %d\n",input[i].name, input[i].age, input[i].sex,input[i].height);
Well, that's never going to happen, so you'll never print anything
5) fflush(stdin); is not a well defined operation on most systems and could lead to undefined behavior, so don't do it.

Resources