I am trying to understand why I am having a zero added on to one of my variables userNumberInput. I have been trying to figure out why this is happening for the a bit without a good solution or explanation. It is only happening in the output file, and does not appear to be happening as a result of the variable being set to 0.
For example if you enter 90 the console shows 90, but the output file shows 900.
#include <stdio.h>
#include <stdlib.h>
void Fibonacci (int userInputNumber);
void UserInput (int* userInputNumber);
FILE *fpOut;
int main(int argc, const char * argv[]) {
//Creating global variable for userInput to be passed from function to function
int userInputNumber = 0;
//Opening file for writing output to
if (!(fpOut = fopen("csis.txt", "w"))) {
printf("csis.text could not be opened for output");
exit(1);
}
//Calling two functions and passing appropriate vaiables to each
UserInput(&userInputNumber);
Fibonacci(userInputNumber);
fclose(fpOut);
return 0;
}
void UserInput (int* userInputNumber) {
//Asks the user for a number for the generator
printf("Enter a number into the Fibonacci Generator: ");
scanf("%d", &*userInputNumber);
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);
//While the user continues to enter a negative number it forces the user to enter a new number
while (*userInputNumber < 0) {
printf("Invalid user input, enter a positive number\n\n");
fprintf(fpOut,"Invalid user input, enter a positive number\n\n");
printf("Enter a number into the Fibonacci Generator: ");
scanf("%d", &*userInputNumber);
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);
}
}
void Fibonacci (int userInputNumber) {
//Defines variables used in this function
int firstNumber, secondNumber, i, seriesNumber, length;
firstNumber = 0;
secondNumber = 1;
seriesNumber = 0;
i = 0;
length = 0;
//For loop that adds the two previous number in the series and prints it and then updates the previous numbers
for (i = 0; seriesNumber < userInputNumber; i++) {
if (i <= 1) {
seriesNumber = i;
length++;
} else {
seriesNumber = firstNumber + secondNumber;
firstNumber = secondNumber;
secondNumber = seriesNumber;
length++;
}
//Statement to break the loop when the next number in the series goes above the user input
if (seriesNumber > userInputNumber) {
length -= 1;
break;
}
//Printing the sequence
printf("%d\n",seriesNumber);
fprintf(fpOut,"%d\n",seriesNumber);
}
//Printing the length of the sequence
printf("Length of the sequence: %d", length);
fprintf(fpOut,"Length of the sequence: %d", length);
}
You have to print a newline after printing the value entered, or 0, which is the first term of the sequence, seems to be appended to the input.
Try changing both of the two
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);
to
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d\n", *userInputNumber);
Related
So, I have to write a program to ask the user for an integer, and then that integer will determine how many more entries the user gets before adding all the numbers that were entered. So, if the first entered integer is "5", then the user can enter 5 more integers. Those 5 integers are then added together at the end and displayed. I have written a program with for loops, but for some reason, it is only adding first 4 integers and not the 5th one. Here is the code:
int main() { //declare main function
int c=0,n,i; //declare integers
int sum=0;
printf("\nEnter an integer: "); //ask user for input and create a label
scanf("%d",&n);
if (n>=0) { //use if statement
for (i=0;i<n;i++) //use for loop inside if statement to account for negative integers
{
sum+=c;
printf("Enter an integer: ");
scanf("%d",&c);
}
}
else {
printf("Wrong number. You can only enter positive integers!");
}
printf("The sum of the %d numbers entered is: %d",i,sum);
return 0;
}
Just change the position of
sum+=c;
to after the scanf it should work.
It is good to split the program. use functions. Not everything in the main function.
int getInteger(void)
{
char str[100];
int number;
while(!fgets(str, 100, stdin) || sscanf(str, "%d", &number) != 1)
{
printf("Wrong input. Try again:") ;
}
return number;
}
int main()
{
int nsamples;
long long sum = 0;
printf("Enter number of samples:");
while((nsamples = getInteger()) <= 0)
{
printf("Try again, entered number must be >= 0\n");
}
printf("Enter numbers:\n");
for(int i = 1; i <= nsamples; i++)
{
printf("Sample no %d:", i);
sum += getInteger();
}
printf("The sim is: %lld\n", sum);
}
Since I am a beginner have been practicing passing arrays as parameters to functions. Could someone explain why this program I wrote works fine on codeblox, but doesn't work in Fedora terminal (on Fedora it doesn't work for any number of scores). I'm using the GCC compiler.
#include<stdio.h>
int num,scores[]={},count,max,sum;
void input(int scores[]);
int findmax(int scores[]);
int findsum(int scores[]);
void display(int max,int sum);
int main()
{
printf("Enter number of scores\n");
scanf("%d",&num);
input(scores);
max=findmax(scores);
sum=findsum(scores);
display(max,sum);
return 0;
}
void input(int scores[])
{
for(count=0; count<num; count ++)
{
printf("Enter score #%d:\n",count);
scanf("%d",&scores[count]);
}
}
int findmax(int scores[])
{
for(count=0; count<num ; count ++)
{
if(scores[count]>max)
{
max=scores[count];
}
}
return max;
}
int findsum(int scores[])
{ sum=0;
for(count=0; count<num ; count++ )
{
sum=sum+scores[count];
}
return sum;
}
void display(int max,int sum)
{
printf("The max score is :%d\nThe total score is:%d\n",max,sum);
}
You should avoid using global variables unless they are absolutely required. None are required here. All values should be declared local to main and should be passed to each function as a parameter, as required.
You must validate ALL input by, at minimum, checking the return of scanf (or whatever input function you are using). If a user simply pressed Enter (generating a '\n') or enters words instead of numbers causing the conversion to fail, you are dead in the water and may well be watching an infinite loop scroll by until you kill the process. (a cat might step on the keyboard, etc.)
When using the scanf family of functions, if a failure occurs, you must account for any characters left in the input buffer (e.g. stdin with scanf). If scanf is called within a loop, you risk an infinite loop where the conversion fails, leaving the same characters in the input buffer only to be read again, and fail, over-and-over again.
If you do not validate your input, you can have no confidence that you are processing a valid input from that point forward, and may in fact be well off into Undefined Behavior. The scanf family of functions returns the number of valid conversions based on the number of format-specifiers contained within the format-string. So with "%d", you have one format-specifier (e.g. %d), so upon successful conversion the return will be 1 (you should also check for EOF if the user manually cancels input with Ctrl + d, or Ctrl + z on windoze -- which is left to you)
Putting those pieces together, you could do something like the following:
#include <stdio.h>
#include <limits.h> /* for INT_MIN */
#define MAX 512
void input (int *scores, int num);
int findmax (int *scores, int num);
int findsum (int *scores, int num);
void display (int max, int sum);
int main (void)
{
int num, scores[MAX] = { 0 }, max, sum;
printf ("Enter number of scores: ");
if (scanf ("%d", &num) != 1) { /* VALIDATE ALL input */
fprintf (stderr, "error: invalid integer input.\n");
return 1;
}
input (scores, num);
max = findmax (scores, num);
sum = findsum (scores, num);
display (max, sum);
return 0;
}
void input (int *scores, int num)
{
int count = 0;
while (count < MAX && count < num) { /* always protect array bounds */
printf ("Enter score [%d]: ", count);
while (scanf ("%d", &scores[count]) != 1) { /* VALIDATE input */
fprintf (stderr, "error: invalid input, try again.\n");
/* remove invalid chars from input buffer */
for (int c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
goto badval;
}
count++;
badval:;
}
}
int findmax (int *scores, int num)
{
int max = INT_MIN, count;
for (count = 0; count < num; count++)
if (scores[count] > max)
max = scores[count];
return max;
}
int findsum (int *scores, int num)
{
int sum = 0, count;
for (count = 0; count < num; count++)
sum = sum + scores[count];
return sum;
}
void display (int max, int sum)
{
printf ("\nThe max score is :%d\nThe total score is:%d\n", max, sum);
}
Example Use/Output
$ ./bin/maxminsum
Enter number of scores: 5
Enter score [0]: 9
Enter score [1]: 3
Enter score [2]: 7
Enter score [3]: 8
Enter score [4]: 2
The max score is :9
The total score is:29
With Error Correction
$ ./bin/maxminsum
Enter number of scores: 5
Enter score [0]: 9
Enter score [1]: 3
Enter score [2]: foo
error: invalid input, try again.
Enter score [2]: 7
Enter score [3]: 8
Enter score [4]: bar
error: invalid input, try again.
Enter score [4]: 2
The max score is :9
The total score is:29
Leave a comment if you have further questions.
This question already has answers here:
Check if a value from scanf is a number?
(2 answers)
Closed 9 years ago.
my program adds numbers entered by the user. It runs and works great until a character is entered instead of an integer. Is there a simple way to make sure only integers are entered from the keyboard?
Here is my code.
#include<stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int n, sum = 0, i, TotalOfNumbers;
printf("Enter the number of integers you want to add\n");
scanf("%d", &n);
printf("Enter %d integers\n",n);
for (i = 1; i <= n; i++)
{
scanf("%d",&TotalOfNumbers);
sum = sum + TotalOfNumbers;
}
printf("Sum of entered integers = %d\n",sum);
return 0;
}
You need to check the return value of scanf. If the input was a valid number, it will return 1. If the input was not a valid number, it will return something else. Here is your code modified to put the checks in.
#include<stdio.h>
#include <stdlib.h>
int get_number()
{
int num;
int ret;
ret = scanf("%d", &num);
if (ret != 1) {
printf("bad number\n");
exit(EXIT_FAILURE);
}
return num;
}
int main(int argc, char **argv)
{
int n, sum = 0, i, TotalOfNumbers;
printf("Enter the number of integers you want to add\n");
n = get_number();
printf("Enter %d integers\n",n);
for (i = 1; i <= n; i++)
{
TotalOfNumbers = get_number();
sum = sum + TotalOfNumbers;
}
printf("Sum of entered integers = %d\n",sum);
return 0;
}
Check the ferror state on the input stream
scanf("%d",&TotalOfNumbers);
if(!ferror(stdin)){
sum = sum + TotalOfNumbers;
}
In addition to posted answer, there options not general as posted, but quicker.
First if you want to skip some final set of characters.In following example all letters,! and + will be skiped
int n;
scanf("%*[a-zA-Z!+]%d",&n);
printf("\n%d",n);
for input
weweqewqQQWWW!!!!+++3332
the output is
3332
Next option is to use buffer wich allowed to read everything untill number is met, and then read the number. The disadvantage is that buffer size is limited
char buf[25];
int n;
scanf("%[^0-9]%d",buf,&n);
printf("\n%d",n);
For input
fgfuf#$#^^#^##4565
Output
4565
I want to print multiple values on same line and then go to next line and print the same values and goes to next line and so on.
for ex:-
3 5 10
2 7 15
in C language.
#include <stdio.h>
int main()
{
int a,b,n,i,j,l;
printf("Enter total digit in a line:");
scanf("%d",&n);
printf("Enter number of lines:");
scanf("%d",&l);
for(i=1;i<=l;i++)
{
for(j=1;j<=n;j++)
{
printf("enter values for line :");
scanf("%d",&n);
}
}
}
For each line, read input as string with e.g. fgets, then use e.g. strtok in a loop to extract each number and use strtol to convert the numbers to integer values, and add them up.
The above solution contains of four parts, so lets split it up and do one at a time.
For each line, read input with fgets.
This is pretty simple, as all you have to do is use your outer loop and ask the user to enter numbers there, as well as read the input there as well:
for (i = 1; i <= l; i++)
{
printf("Enter numbers for line number %d: ", i);
char input[128];
fgets(input, sizeof(input), stdin);
}
Use strtok in a loop to extract each number from the input.
for (i = 1; i <= l; i++)
{
/* The code to read the input... */
char *pointer = strtok(input, " ");
while (pointer != NULL)
{
/* `pointer` is now pointing to the next space-delimited number */
/* Find the next space-delimited number */
pointer = strtok(NULL, " ");
}
}
Use strtol to convert the numbers to integer values.
{
/* `pointer` is now pointing to the next space-delimited number */
/* Convert string to number */
long value = strtol(pointer, NULL, 10);
/* Find the next space-delimited number... */
}
Finally add all values in the line.
for (i = 1; i <= l; i++)
{
long sum = 0;
/* ... */
{
long value = strtol(pointer, NULL, 10);
sum += value;
}
printf("The sum of all values on line %d is %ld\n", i, sum);
}
Putting it all together, we get this code:
for (i = 1; i <= l; i++)
{
printf("Enter numbers for line number %d: ", i);
char input[128];
fgets(input, sizeof(input), stdin);
long sum = 0;
char *pointer = strtok(input, " ");
while (pointer != NULL)
{
/* `pointer` is now pointing to the next space-delimited number */
/* Convert string to number */
long value = strtol(pointer, NULL, 10);
sum += value;
/* Find the next space-delimited number */
pointer = strtok(NULL, " ");
}
printf("The sum of all values on line %d is %ld\n", i, sum);
}
Note: The above code have no error checking. I leave that as an exercise to the readers.
E.g.
#include <stdio.h>
int main(void){
int n, l, i, j;
printf("Enter total digit in a line:");
scanf("%d", &n);
printf("Enter number of lines:");
scanf("%d", &l);
for(i=1;i<=l;i++){
long sum =0;
printf("enter values for line : ");
for(j=1;j<=n;j++){
int num;
scanf("%d", &num);//n : Names are colliding
sum += num;
}
printf("sum of line : %ld\n", sum);
}
return 0;
}
I am very new to C. I am using A modern Approach to C programming by King 2nd Edition.
I am stuck on chapter 6. Question 1: Write a program that finds the largest in a series of numbers entered by the user. The program must prompt the user to enter the numbers one by one. When the user enters 0 or a negative number, the program must display the largest non negative number entered.
So far I have:
#include <stdio.h>
int main(void)
{
float a, max, b;
for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}
printf("Largest non negative number: %f", max);
return 0;
}
I do not understand the last part of the question, which is how to see which non-negative number is the greatest at the end of user input of the loop.
max = a > a ???
Thanks for your help!
So you want to update max if a is greater than it each iteration thru the loop, like so:
#include <stdio.h>
int main(void)
{
float max = 0, a;
do{
printf("Enter number:");
/* the space in front of the %f causes scanf to skip
* any whitespace. We check the return value to see
* whether something was *actually* read before we
* continue.
*/
if(scanf(" %f", &a) == 1) {
if(a > max){
max = a;
}
}
/* We could have combined the two if's above like this */
/* if((scanf(" %f", &a) == 1) && (a > max)) {
* max = a;
* }
*/
}
while(a > 0);
printf("Largest non negative number: %f", max);
return 0;
}
Then you simply print max at the end.
A do while loop is a better choice here because it needs to run at least once.
#include<stdio.h>
int main()
{
float enter_num,proc=0;
for(;;)
{
printf("Enter the number:");
scanf("%f",&enter_num);
if(enter_num == 0)
{
break;
}
if(enter_num < 0)
{
proc>enter_num;
proc=enter_num;
}
if(proc < enter_num)
{
proc = enter_num;
}
}
printf("Largest number from the above is:%.1f",proc);
return 0;
}