Retrieving User Input for Arrays in C - c

Beginner programming including arrays and I'm having trouble just getting user input for the arrays. The printf functions I've included are just to check whether my arrays are working, the larger program I'm writing just needs to use these two arrays.
The input for the char array seems to work fine, I've tried a couple of different methods. However, the int array doesn't seem to work using the same diversity of methods I've used successfully with the char array. Not sure what I'm missing. Below is the code and the output when I run the program:
int main()
{
char grades[5]; // create array to store letter grades
int hours[5]; // array to store hours
puts("Please enter letter grades:"); // Input letter grades using fgets
fgets(grades, 5, stdin);
printf("Letter grade for course 3 is %c.\n", grades[2]);
int x = 0;
puts("Please enter course hours:\n");
for (x = 0; x < 5; x++)
{
scanf("%d", &hours[x]);
}
printf("Course hours for course 2 are: %d.\n", hours[1]);
return 0;
}
Output of this code:
Please enter letter grades:
ABCDF <- user input
Letter grade for course 3 is C.
Please enter course hours:
Course hours for course 2 are: -858993460.
Press any key to continue . . .

fgets(grades, 5, stdin); captures ABCD of the input leaving F in the input stream. scanf("%d", &hours[x]); can't parse an int from F though it tries five times. Each failure leaves the F in the input stream.
Make buffers large enough for typical input.
Use fgets for all input. Parse with sscanf or others. Use the return of sscanf to make sure the parsing was successful.
#include <stdio.h>
int main( void)
{
char grades[50] = ""; // create array to store letter grades
char line[50] = "";
int hours[5] = { 0}; // array to store hours
int result = 0;
puts("Please enter letter grades:"); // Input letter grades using fgets
fgets(grades, sizeof grades, stdin);
printf("Letter grade for course 3 is %c.\n", grades[2]);
int x = 0;
for (x = 0; x < 5; x++)
{
do {
printf("Please enter course %d hours:\n", x + 1);
fgets ( line, sizeof line, stdin);
result = sscanf( line, "%d", &hours[x]);
if ( result == EOF) {
printf ( "EOF\n");
return 0;
}
} while ( result != 1);
}
printf("Course hours for course 2 are: %d.\n", hours[1]);
return 0;
}

Related

Words frequency with number of letters (basic loop only)

I Want to write C program to print words length and their frequency by letters number with basic loops techniques. I could get the word length work but I stuck with frequency
(example: Do 2 not 3 judge 5 a 1 book 4 (had solved this))
there are # words with 1 letter
there are # words with 2 letter
etc...
#include <stdio.h>
int main(void) {
char word[30];
int i = 0,b=0,c=0,j=0,d=0;
printf("Please enter a word: ");
for (i = 0; i < 30 ; i++){
scanf("%s", word);
while (word[b]!='\0'){
b++;
}
printf("%s %d ", word, b);
b = 0;
}
return 0;
}
Your question wasn't completely clear. But from what I understood, you also wanted to print the number of times(frequency) a word of length 'l' is inputted by the user. So I will answer that :
You could just store the length of the word in an array that the user inputs. Once all the inputs are read, you can just print the frequency of each word length from the stored array
Refer the following code to understand what I meant :
#include <stdio.h>
int main(void) {
char word[30];
int i = 0,b=0,c=0,j=0,d=0;
int word_length_freq[30]={0}; //an array which will store the frequency of word length(all initialized to 0)
//eg. if word is "hello" it will increase count of word_length_freq[5] by 1
printf("Please enter a word: ");
for (i = 0; i < 3 ; i++){
scanf("%s", word);
while (word[b]!='\0'){
b++;
}
word_length_freq[b]++;
printf("%s %d ", word, b);
b = 0;
}
for(int i=1;i<30;i++){ //This will print the frequency of all words from length 1 to 30
printf("There are %d words of length %d\n",word_length_freq[i],i);
}
return 0;
}
I hope this solves your question !

C scanf ignore second variable in loop [duplicate]

This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Why does scanf ask twice for input when there's a newline at the end of the format string?
(7 answers)
Closed 3 years ago.
int main()
{
float T[100];
float *pt=T;
float suma = 0, srednia, zmienna;
int rozmiar;
printf("How many numbers would you like to put in: ");
scanf(" %d", &rozmiar);
int dzielnik = rozmiar;
printf("\n Enter the number: \n");
for(int i = 0;i<rozmiar;i++)
{
printf("\n i = %d", i );
scanf("%99f\n", &zmienna);
*(pt+i) = zmienna;
}
return 0;
}
This is my code. The idea is simple. I have an array; I want to scan how many numbers I want to put into the array and then put numbers into array. I don't know why but scanf ignores the second variable that I put in array.
If I put "2" in first scanf, program wants 3 variables from me.
My output should be like this:
How many numbers would you like to put in: 2
Enter the number:
i = 0
2 (my number)
i=1
3 (my number)
but it's actually like this:
How many numbers would you like to put in: 2
Enter the number:
i = 0
1 (my number)
2 (my number)
i = 1
3 (my number)
The specific problem you were having is with scanf: putting a \n is generally a bad idea because entering a newline is generally how you send off a line of characters to the program. Use '\n' liberally in printf and "never" with scanf.
Here's my modified version. I removed the pointer shenanigans because indexing into the array is simpler and better, and also initialized the array which you should always do:
#include <stdio.h>
int main() {
float T[100] = {0}; // Used to not be initialized.
float suma = 0, zmienna;
int rozmiar;
printf("How many numbers would you like to put in: ");
scanf("%d", &rozmiar);
printf("\n Enter the number: \n");
for (int i = 0; i<rozmiar; i++) {
printf("\n i = %d", i);
scanf("%f", &zmienna);
T[i] = zmienna;
}
return 0;
}

How i cannot ignore 0(zero) as a grade?

int main(){
char students_number[30], students_grade[30];
char *number, *value;
int flag=0, students, i, grade, a=0, b=0, c=0, d=0, f=0;
float sum=0;
while(flag==0) // This while loop exist just because to run program until the number of students will be given correct..
{
printf("Please enter the number of students (It must be between 1-100): ");
scanf("%s",&students_number); // This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
students = strtol(students_number, &number, 10); // strtol is a function of stdlib.h and checks the variable is whether int or not for this program..
if(students<=100 && students>0)
{
for(i=1;i<=students;i++)
{
printf("Please enter %d. student's grade (in integer form):",i);
scanf("%s",&students_grade);// This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
grade = strtol(students_grade, &value, 10); // This line checks the grade which was given is integer or not by using strtol which is in the stdlib.h..
if(grade<0 || grade>100 || grade=='\0')
{
printf("The grade of the student was given incorrect!\n");
i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..
}
else
{
if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
f++;
else if(grade<=60 && grade>=51)
d++;
else if(grade<=73 && grade>=61)
c++;
else if(grade<=85 && grade>=74)
b++;
else if(grade<=100 && grade>=86)
a++;
sum += grade;
}
}
sum /= students; // This command divides the sum of the grades to number of the students to get the average results in the class..
printf("\nThe average result of the class is %.2f..\n",sum);
printf("\nThe letter form of the all results are:\nNumber of F: %d\nNumber of D: %d\nNumber of C: %d\nNumber of B: %d\nNumber of A: %d\n",f,d,c,b,a);
flag = 1; // As it was mentioned before, this commands exist to break the while loop because the program was done successfully..
}
else // This if command controls the number of students wheter was given right or not..
{
printf("Please enter a proper number of students.\n");
flag = 0;
}
}
return 0;
}
Hello, this is my first question. I had to create a program which calculates the average of the results. But when i enter 0(zero) as a grade then it doesn't allow it just because i tried to exclude the every types except int type.
How can i make this correct?
You can use scanf to read a number and check that scanf done correctly its work:
from man scanf:
Return Value
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
So you can check that you've read an integer with scanf, without writing if (value == '\0'), which prevents you to read 0 grades...
for(i=1;i<=students;i++)
{
int ok;
printf("Please enter %d. student's grade (in integer form):",i);
/* read line from input. Why using fgets instead of scanf directly? See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html*/
if (NULL == fgets(students_grade, sizeof students_grade, stdin))
{
perror("fgets");
exit(1);
}
/* **try** to parse what have been read */
ok = sscanf(students_grade, "%d", &value);
/* check that scanf has done its work */
if (1 != ok)
{
printf("The grade of the student was given incorrect!\n");
i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..
}
else
{
if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
f++;
/* ... */
}
I also advice you to read this article: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html.

My program compiles and when ran, it doesn't give me the input i put in

The purpose of my program thus far is to create 4 arrays. 1 'char' array which will take in 10 different string values with each element having a maximum of 25 characters. And 3 other array's that will take in 10 integer values and store them into my array. I compile and run my program, and cycle through my for loops and once completed, I get some weird integer values in the place of my teamName array, and for the 'teamWins' 'teamLosses' and 'teamTies' arrays, it gives me the first value I input for ALL elements in those arrays. I really want to understand how arrays work but I am having trouble declaring them, and using them with input, and output. Can anyone see and explain how I can take in 10 strings with values of 25 characters in each element, and take in 10 integers in the other 3 arrays with elements of 10? I will attach my source code below.
#include <stdio.h>
#include <stdlib.h>
#define NUM_TEAM 10
void displayWelcome(void);
int main(void)
{
char * teamName[NUM_TEAM + 1][30] = { "" };
int teamWins[NUM_TEAM] = {0};
int teamLosses[NUM_TEAM] = {0};
int teamTies[NUM_TEAM] = {0};
int i, bestPercent, worstPercent;
displayWelcome();
//Team Name
for (i = 0; i < NUM_TEAM; i++)
{
//Prompt and enter team name
printf("Enter %i's team name: ", i + 1);
fgets (teamName[NUM_TEAM], sizeof teamName[NUM_TEAM], stdin);
//Data validation
}
//Team wins
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter wins for team number %i : ", i + 1);
scanf("%i", &teamWins[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamWins) || teamWins <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Team losses
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter losses for team number %i : ", i + 1);
scanf("%i", &teamLosses[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamLosses) || teamLosses <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Team ties
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter ties for team number %i : ", i + 1);
scanf("%i", &teamTies[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamTies) || teamTies <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Display Data
for (i = 0; i < NUM_TEAM; i++)/* output each word read */
{
printf("%s", teamName);
printf("wins losses ties\n");
printf("%i %i %i\n", teamName[i], teamWins[i], teamLosses[i], teamTies[i]);
}
return 0;
}
void displayWelcome(void)
{
printf("Welcome to my Football Stats\n\n");
}
You've got four issues:
Declaring teamName as char * teamName[NUM_TEAM + 1][30] = { "" }; is incorrect; if you want an array of strings, it's sufficient to declare char teamName[NUM_TEAM + 1][30] = { "" }; (you want a 2D array of chars, not char *s).
In fgets (teamName[NUM_TEAM], sizeof teamName[NUM_TEAM], stdin);, you're writing each team name to the same unused element. Instead, use fgets (teamName[i], sizeof teamName[NUM_TEAM], stdin); to write to the proper team during each iteration.
Printing using printf("%s", teamName); is incorrect; you want to print each team name rather than attempt to print the address of the teamName array: printf("%s", teamName[i]);
You have an extra argument in printf("%i %i %i\n", teamName[i], teamWins[i], teamLosses[i], teamTies[i]);; since you've already printed teamName[i] in Point 3, you should remove it in this printf() call: printf("%i %i %i\n", teamWins[i], teamLosses[i], teamTies[i]);

Another way to terminate loop?

I'm studying loops in class and for one of the labs, I have to figure out a way for the user to enter an unspecified number of integers to calculate the average. I know I can have the user enter the number of integers to be averaged in order for the loop to be terminated like below:
int count = 0, value = 0, sum = 0, numberofintegers = 0;
double avg = 0;
printf("enter the number of integers you wish to average\n");
scanf("%d",&numberofintegers);
//loop
while (count < numberofintegers)
{
printf("enter a positive integers\n");
scanf("%d",&value);
sum = sum + value;
count = count + 1;
}
avg = (double) sum/count;
So basically I could have a user input the number of integers to be averaged in order for the loop to terminate, but there has to be another way to make the loop terminate without having the user input it?
Normally you'd use a predetermined "illegal" number like (say -1)
input = read_a_value();
while(input != -1)
{
// do something with input
input = read_a_value();
}
scanf returns the number of successful entries.
This may solve your issue.
#include<stdio.h>
int main(void)
{
int number, total = 0, count = 0;
char c;
printf("Enter a number to continue, a character to exit\n");
while (scanf("%d", &number) == 1)
{
total+= number;
count++;
}
/* You need to handle the case where no valid input is entered */
(count > 0) ? printf("Average : %.2f\n", (float)total / count) : printf("No valid numbers entered\n");
/* I have casted the average to float to keep the precision*/
while (getchar() != '\n')
;;
printf("Press any key to continue..");
getchar();
return 0;
}
A downfall is that the scanf will continue to prompt for input if a user presses the Enter Key repeatedly. In fact you might wish to replace the scanf with fgets. Have a look here.
If you are sure that the user doesn't enter too many numbers, use a string.
Length of string, you can choose according to you and split it using spaces to get the numbers

Resources