while loop asks user input one time only - c

#include <stdio.h>
#include <stdlib.h>
struct the_struct
{
char FirstName[20];
char LastName[32];
int Score[20];
};
int main ()
{
int i,n;
struct the_struct *ptr[100];
printf("how many students?\n");
scanf("%d",&n);
while (i<=n);
{
i==0;
ptr[i] = malloc(sizeof(struct the_struct));
printf("Enter First Name \n");
scanf("%s",ptr[i]->FirstName);
printf("Enter Last Name \n");
scanf("%s",ptr[i]->LastName);
printf("Enter Score? \n");
scanf("%s",ptr[i]->Score);
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
i++;
}
}
hey guys, so when i enter the first input, it goes only once without going on for the number the user inputs, i tried the for loop but same result.
still learning C so my apology if i misunderstood something.
Thanks in advance.

Your while loop is problematic. You could rewrite it as:
for (i = 0; i < n; ++i)
{
ptr[i] = malloc(sizeof(struct the_struct));
printf("Enter First Name \n");
scanf("%s",ptr[i]->FirstName);
printf("Enter Last Name \n");
scanf("%s",ptr[i]->LastName);
printf("Enter Score? \n");
scanf("%s",ptr[i]->Score);
printf("%s %s %s\n",ptr[i]->FirstName,ptr[i]->LastName,ptr[i]->Score);
}
And since you use %s to read and print Score, you should declare it as char Score[20]; instead of int.

The problem is that i is uninitialized. Therefore, the loop while (i <= n) has undefined behavior, and can end at any time.
Add int i = 0 initializer to fix this problem.
Notes:
i == 0 expression at the beginning of the loop has no effect
Since i starts at zero, your while loop should be while (i < n), not <=.
You should check the results of scanf to see if the user entered something meaningful
You should specify the size of the array into which you read a string, e.g. scanf("%31s",ptr[i]->LastName); This prevents buffer overruns.

Related

How do you use scanf in a for loop so it does not stop looping on the first try?

for(int i=0;i<num; i++)
{
char word[32];
scanf(" %[^\n]s",word);
makeDictionary(word, readDictionary);
}
I have a program where I want to ask user for certain strings n times (with spacing allowed). However, when they input for example n = 2, it only loops once and exists. I know there is something wrong with my scanf.
I do Java and I'm a beginner at C. The way strings are done is very different.
This code can help you:
#include <stdio.h>
#include <string.h>
int main()
{
int N;
do
{
printf("Give me number of words :");
scanf("%d",&N);
}while(N<1);
for(int i=0;i<N;i++)
{char str[20];
printf("\nGive me the %d word :",i+1);
scanf("%s[^\n]",str);
printf("%s",str);
}
}

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 Why does the for loop only not iterate as many times as its supposed to?

I'm trying to ask K amounts of words to add them in a matrix.
And i have 2 problems:
I tried to make the condition that the strlen(string) must be less than the size of n(matrix size). But when it enters the do while loop, it never quits.
How can i make the for loop to repeat until k words are entered?
I already tried a few days ago, and the do while worked fine. Until i changed something and it got messy.
/* Enter the matrix dimension */
int n;
do{
printf("\nEnter the matrix size");
scanf("%d", &n);
}while(2>n);
/* Ask for the amount of words the user will enter */
int k;
do{
printf("\nInsert how many words you will enter:");
scanf("%d", &k);
}while(k<0);
/* k Words loop */
int amountOfWords=0;
char string[20];
int i;
for(i=0; i<k; i++, amountOfWords++)
{
do {
printf("\nEnter the %d word:\n", amountOfWords+1);
scanf("%s", &string);
}while(strlen(string) > n);
}
The problem with your current code is that the amountOfWords variable is never incremented inside the do-while loop, so the condition for the loop strlen(string) > n is always true.
Here is one way to fix the problem:
int amountOfWords=0;
char string[20];
for(int i=0; i<k; i++)
{
do {
printf("\nEnter the %d word:\n", i+1);
scanf("%s", string);
}while(strlen(string) > n);
amountOfWords++;
}
In this way, if the user enters a word that is longer than the maximum size (n), the loop will ask again for a word until a valid word is entered, and the variable amountOfWords will be incremented after a valid word is entered.
Another way to do it could be using a while loop, like this:
int amountOfWords=0;
char string[20];
int i=0;
while(amountOfWords<k)
{
printf("\nEnter the %d word:\n", amountOfWords+1);
scanf("%s", string);
if(strlen(string) <= n)
{
amountOfWords++;
}
}
In this way, the loop will keep running until amountOfWords reaches the desired amount of words (k).

How to get multiple inputs in one line in C?

I know that I can use
scanf("%d %d %d",&a,&b,&c):
But what if the user first determines how many input there'd be in the line?
You are reading the number of inputs and then repeatedly (in a loop) read each input, eg:
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av)
{
int numInputs;
int *input;
printf("Total number of inputs: ");
scanf("%d", &numInputs);
input = malloc(numInputs * sizeof(int));
for (int i=0; i < numInputs; i++)
{
printf("Input #%d: ", i+1);
scanf("%d", &input[i]);
}
// Do Stuff, for example print them:
for (int i=0; i < numInputs; i++)
{
printf("Input #%d = %d\n", i+1, input[i]);
}
free(input);
}
Read in the whole line, then use a loop to parse out what you need.
To get you started:
1) Here is the manual page for getline(3):
http://man7.org/linux/man-pages/man3/getline.3.html
2) Some alternatves to getline:
How to read a line from the console in C?
3) Consider compressing spaces:
How do I replace multiple spaces with a single space?
4) Use a loop for parsing. You might consider tokenizing:
Tokenizing strings in C
5) Be careful and remember that your user could enter anything.
#include <conio.h>
#include <stdio.h>
main()
{
int a[100],i,n_input,inputs;
printf("Enter the number of inputs");
scanf("%d",&n_input);
for(i=0;i<n_input;i++)
{
printf("Input #%d: ",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n_input;i++)
{
printf("\nInput #%d: %d ",i+1,a[i]);
}
}
/*
_______________This program is in C Programming Language_______________
We have to directly enter all the elements in one line giving spaces between them. Compiler will automatically ends the for loop I have used and assign the value to their respective variables or array indexes. Below program and output will give you better understanding.
*/
#include <stdio.h>
int main()
{
//taking no of inputs from user
int len;
printf("Enter the number of inputs you want to enter : ");
scanf("%d", &len);
int i;
//defined an array for storing multiple outputs
int arr[100];
//included a printf statement for better understanding of end user
printf("Enter the inputs here by giving space after each input : ");
/*here is the important lines of codess for taking multiple inputs on one line*/
for (i=0;i<len;i++)
{
scanf("%d", &arr[i]);
}
printf("Your entered elements is : ");
for (i=0;i<len;i++)
{
printf("%d ", arr[i]);
}
}
/*
OUTPUT :
Enter the number of inputs you want to enter : 5
5 5 5 8 7
Your entered elements is : 5 5 5 8 7
*/

Expression must have class type error

I'm working on a homework assignment and I've hit a brick wall. I think I have all of the code that I need, I just need to get the program to compile. The object of the assignment is
Create a structure to hold student names and averages. The structure should contain a first name, last name and an integer grade average.
Then:
Write a program that will do the following:
1.) Create an array of pointers to these student structures.
2.) Prompt the user for names and averages.
3.) After you get the student’s information use malloc to provide the memory to store the information.
4.) Place the address of the student, returned by malloc, into the pointer array.
5.) AFTER the user indicates there are no more students:
Search the data entered and find the highest and lowest grade
average.
a)Print the name and grade for the highest grade
b)Print the name and grade for the lowest grade
c)Print the average of all grades entered
Here is my code:
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
#define SIZE 25
int enterStudents (int ePointArray[SIZE]);
void searchData (int *sPointArray, int *sHigh, int *sLow);
int calculateAvg (int, int *avgPointArray);
void printData (int, int *pHigh, int *pLow);
struct student
{
char firstName[20];
char lastName[20];
int average;
};
int main()
{
int pointArray[SIZE], high[3], low[3];
int i = 0, studentCounter, avgGrade;
for (i = 0; i < SIZE; i++)
pointArray[i] = 0;
studentCounter = enterStudents(pointArray);
searchData(pointArray, high, low);
avgGrade = calculateAvg(studentCounter, pointArray);
printData(avgGrade, high, low);
return 0;
}
int enterStudents (int ePointArray[SIZE])
{
char tempFname[20], tempLname[20], yesNo[2] = "y";
int tempAvg, counter = 0;
int *studPtr;
struct student aStud={"\0", "\0", 0};
while( counter < SIZE && strcmp(yesNo, "y")==0)
{
printf(" Enter first name: ");
scanf("%s", tempFname);
printf(" Enter last name: ");
scanf("%s", tempLname);
printf(" Enter grade average:");
scanf("%d", tempAvg);
strcpy(aStud.firstName, tempFname);
strcpy(aStud.lastName, tempLname);
aStud.average = tempAvg;
studPtr = malloc(sizeof(struct student));
ePointArray[counter] = *studPtr;
counter++;
printf("/n");
printf(" Do you have more students? yes or no:");
scanf("%s", yesNo);
}
return counter;
}
void searchData (int sPointArray[SIZE], int sHigh[3], int sLow[3])
{
int searchCounter = 0;
while( searchCounter = 0)
{
if( *sPointArray[searchCounter].average > *sPointArray[searchCounter+1].average)
{
sHigh[0] = &sPointArray[searchCounter].firstName;
sHigh[1] = &sPointArray[searchCounter].lastName;
sHigh[2] = &sPointArray[searchCounter].average;
}
if( *sPointArray[searchCounter].average < *sPointArray[searchCounter+1].average)
{
sLow[0] = &sPointArray[searchCounter].firstName;
sLow[1] = &sPointArray[searchCounter].lastName;
sLow[3] = &sPointArray[searchCounter].average;
}
searchCounter++;
}
}
int calculateAvg( int totalStudents, int avgPointArray[SIZE])
{
int sum = 0;
int avgCounter;
double overallAvg;
for( avgCounter = 0; avgCounter < totalStudents; avgCounter++)
sum = sum + *avgPointArray[avgCounter].average;
overallAvg = sum/totalStudents;
return overallAvg;
}
void printData (int pAverage, int pHigh[3], int pLow[3])
{
printf(" Highest Grade: %s %s %d", pHigh[0], pHigh[1], pHigh[3]);
printf("/n");
printf(" Lowest Grade: %s %s %d", pLow[0], pLow[2], pLow[3]);
printf("/n");
printf(" Average Grade: %d",pAverage);
}
The main chunk of problems come from the searchData function. In the if statements, every occurrence of *sPointArray and &sPointArray is underlined in red and the error reads
"Error: expression must have class type"
The same thing also happens in the calculateAvg function with *avgPointArray in the for loop. I know that the error is a fairly common problem for noobie C programmers (i.e myself) and that it generally has to do with writing the code as a function instead of a statement or something like that, but I can't for the life of me find where I have went wrong. Any help would be highly appreciated. I've been working at this for so long my vision is blurring.
Also, for anyone who solves this in like two seconds and wants proof that I'm a true idiot, there is an error in the enterStudents function where it says StudPtr = malloc(sizeof...). The error shows under the assignment symbol and says
"Error: a value of type "void*" cannot be assigned to an entity of type "int*".
I understand this concept in theory, but some advice for how to fix it would be highly appreciated.
Thank you in advance for any help.
You declare the sPointArray as an array of integers, but use it as an array of structures.

Resources