This is a simple program to compute ages of people in the room.
I am at the very initial stage, and now I see that I do not know which variables (I mean variables that I declare before scanf and then placeholders within scanf) to use for scanf; how to choose and apply a correct variable. Is there a resource that could explain in plain English these issues?
Here is the program:
// Ages people by a year. Arrays
#include <stdio.h>
int main (void)
{
// determine number of people
int n;
do
{
printf("Number of people in room: ");
scanf ("%i", &n);
}
while (n<1); // get the number of people in the room, pass through user
// again and again until the user gives a positive integer
// declare array in which to store everyone's age
int ages[n];
int i;
for (i = 0; i < n; i++)
{
printf("Age of person #%i: ", i + 1); // person number 1, person number 2, etc
scanf ("%d", ages[i]); // store the age in the i-th part of the array ages
}
// report everyone's age a year hence
printf("Time passes...\n\n");
for (i = 0; i < n; i++)
{
printf(" A year from now person #%i will be %i years old.\n", i + 1, ages[i] + 1);
// we add 1 year to previous age
}
}
scanf("%d") expects an address as an argument. Therefore, replace
scanf ("%d", ages[i]);
with
scanf ("%d", ages + i);
(or &ages[i] but that's personal preference.)
scanf expects pointer to some variable in order to change it's value - otherwise it will get some copy that won't affect the real variable.
this line :
scanf ("%d", ages[i]);
dereference ages and returns an integer, not a pointer to an integer.
change it to be
scanf ("%d", &ages[i]);
the & will extract the memory address of ages[i] and pass it as a pointer to scanf
Related
#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;
}
I've been trying to convert my python to C code and it's my first time using C.
Basically I want it to ask how many grades I will input and then put them in an array. The problem is that the amount keeps putting in the array. I thought that I could declare the size of the array after asking how many grades I was inputting but I think that's the problem. I am not sure how else to do it. I have a lot of printfs I was using for debugging.
Any Suggestions?
double enter_quiz_grades()
{
int quiz_amount,loop,i;
printf("Enter number of quiz grades to enter:");
scanf(" %d \n", &quiz_amount);
printf("You typed %d students\n",quiz_amount);
double temp=0;
double grades[quiz_amount];
for (loop = 0; loop<quiz_amount;loop++)
{
printf("loop is %d", loop);
i = loop+1;
printf("Enter grade for quiz %d: ",i);
scanf("%lf\n", &temp);
grades[loop] = temp;
printf("%lf",grades[loop]);
}
return 0.0;
}
The problem is you are using '\n' inside scanf. Also you can get rid of additional variables.
Here is the modified code:
double enter_quiz_grades() {
int quiz_amount, i;
printf("Enter number of quiz grades to enter:");
scanf("%d", &quiz_amount);
printf("You typed %d students\n",quiz_amount);
double temp = 0;
double grades[quiz_amount];
for (i = 0; i < quiz_amount; i++)
{
printf("loop is %d\n", i);
printf("Enter grade for quiz %d: ", i + 1);
scanf("%lf", &grades[i]);
printf("%lf\n",grades[i]);
}
return 0.0;
}
Just a small detail, not strictly related to the original question:
double grades[quiz_amount];
This creates an array, sized at runtime, from a variable. If this variable is read from somewhere, this can lead to a malicious user giving it a very high (or ngative!) value, and you are in big problems. The linux kernel is removing them from the source for this exact reason (as this syntax creates the array in the stack - attacker can modify the return address). Make this a dynamic array allocated on the heap (malloc()).
https://www.phoronix.com/scan.php?page=news_item&px=Linux-Kills-The-VLA
Currently I am writing a simple program in C that reads in values the user enters in a loop. For some reason, when I initialize the integer a I am given a random value as opposed to the value I specified. Any help would be greatly appreciated
#include <stdio.h>
int main()
{
char sName[10];
int sTime;
int a = 0;
printf("%d", &a);
printf("Please enter the name of your snail: ");
scanf("%s", &sName);
for(a = 10; a < 20; a = a + 1) {
printf("%d", &a);
printf("Please enter the %d time of your snail: ", &a + 1);
scanf(" %d ", &sTime);
}
return 0;
}
Change this:
printf("%d", &a);
to this:
printf("%d", a);
&a is the address of a (and it's of type int*, so %d is the wrong format). a gives you the value of a.
You still need the & in scanf(" %d ", &sTime);; scanf needs the address of sTime so it knows where to store the value.
You're printing the address of a. You don't want the & in there:
printf("%d", a);
You do want the & for scanf() because you need to tell that function where (at what address) to store the value.
I am writing a program to scan the name, gender, and three monthly checks for a person. Here is an example on what I want entered:
Jack m 200 250 300
If the user types "Enough" and presses enter without filling the other details I want the loop to end. I tried using two scanf's, one for the string alone and one for the others but it doesn't loop properly. Here is my code:
int main()
{
int i;
char names[SIZE][NAME_LEN] = {0}, gender[SIZE] = {0};
int sales[SIZE][SALES_LEN] = {0};
printf("Enter the name, gender and three month sales for name %d: ", i+1);
for (i=0; i<SIZE; i++){
if (strcmp(names[i], "Enough") == 0 || strcmp(names[i], "enough") == 0)
break;
scanf("%s %c %d %d %d",names[i], &gender[i], &sales[i][0],&sales[i][1],&sales[i][2]);
}
return 0;
}
Your code is broken is many places: badly ordered statements and wrong kind of reading and parsing. This may do the trick:
for (i=0; i<SIZE; i++) {
char buffer[100]; // A full line
printf("Enter the name, gender and three month sales for name %d: ", i+1);
if (fgets(buffer,sizeof buffer,stdin)==NULL // if nothing can be read
|| strncasecmp(buffer,"-stop",5)) { // or if user typed "-stop" and whatever, an impossible lastname?
break;
}
// try to convert the line into fields of given types...
if (sscanf(buffer,"%s %c %d %d %d",names[i], &gender[i], &sales[i][0],&sales[i][1],&sales[i][2])!=5) {
// do something if conversions failed
}
}
You could use something like this:
while(gets(line)) { ... }
If user presses only the return key the gets function returns NULL and the cycle stops. This way the user doesn't have to type "Enough".
*Don't use the gets() function because it's unsafe (risk of buffer overflow).
I usually wrap it in a function which controls the length of the input.
when i am running the below code to find max literacy rate and max income, the program is taking inputs properly but finally when displaying output for last two printf statements, i am getting the following error "segmentation fault.core dumped."
Please explain what is wrong..Thanks in advance.
#include<stdio.h>
#include<stdlib.h>
#define MAX 50
struct state_det {
char name[50];
long population;
float literacy;
long income;
}s[MAX];
int main()
{
int n,i,max_lit = 0, max_income = 0;
int t, p;
printf("enter number of states\n");
scanf("%d",&n);
for(i = 0; i < n; i++)
{
printf("enter the name of the state %d\n",i);
scanf("%s",&s[i].name);
printf("enter the population of the state %d\n",i);
scanf("%ld",&s[i].population);
printf("enter the literacy rate of the state %d\n",i);
scanf("%f",&s[i].literacy);
printf("enter the average income of the state %d\n",i);
scanf("%ld",&s[i].income);
}
max_lit = s[0].literacy;
max_income = s[0].income;
for(i = 1; i < n; i++)
{
if(max_lit < s[i].literacy) {
max_lit = s[i].literacy;
t = i;
}
if(max_income < s[i].income) {
max_income = s[i].income;
p = i;
}
}
printf("\nthe state with highest literacy is %s and rate = %f\n",s[t].name, s[t].literacy);
printf("\nthe state with highest income is %s and rate = %ld\n",s[p].name, s[p].income);
return 0;
}
The line
scanf("%s",&st[i].name);
should be
scanf("%s",s[i].name);
because specifier %s is looking for char* and you are trying to pass char (*)[50].
t and p are not initialized. If in the data, the 0th element has the maximum income or literacy, then t or p will be undefined and it will be accessing array elements out of bound. This can be confirmed by entering 0th state data with lower values than the subsequent states.
The solution is to initialize t and p to 0.
P.S. : Please indent your code. It is difficult to read.
P.P.S. : max_lit should be float.
P.P.P.S : Some error checking needs to be done (for eg. if n <= 50, etc).
dont use scanf for strings instead use fgets(s[i].name,50,stdin)
since scanf cannot read spaces in a string. Say you enter hello world though the size is less than 50 it only takes hello into consideration and world is not stored in the string because as soon as space character is detected the string reading is terminated by scanf
and also t and p values must be initialized to 0 if the zeroth element is itself the maximum literacy and income. The value of t and p are garbage values
Read them to understand why not to use & for reading strings in scanf
C: why no & for strings in scanf() function?
scanf() does not read input string when first string of earlier defined array of strings in null
why we do not use '&' in scanf for char arrray
Reading a string with scanf