I'm a beginner in C and trying to create a program and having a problem with my main function.
Problem:
After asking how many integers they'd like to enter, for example: 4 numbers, the loop goes on 5 times essentially taking in 5 numbers. It also only prints "Next: " after the 2nd number.
In my while
loop, which I put for error checking, after the user puts a valid method, example: enters 1, it will print out that it's an "invalid choice" and re-asks again only once more.
Code:
#include <stdio.h>
#include<stdlib.h>
#include "a3defs.h"
int main() {
StackType stk;
StackType *stkPtr = &stk;
//Will be used to check whether to use recursive or iterative
int method = 0;
int sum;
int *sumPnt = ∑
//Will be used to create array for amount of ints:
int numOfIntegers;
//Array of ints:
int *userInts;
printf("How many integers would you like to enter? ");
scanf("%d", &numOfIntegers);
userInts = (int*)calloc(numOfIntegers, sizeof(int)); //Create the array
printf("Please enter %d numbers: \n", numOfIntegers);
int i;
for (i = 0; i < numOfIntegers; i++) {
scanf("%d\n", &userInts[i]);
printf("Next:");
}
while(1) {
printf("Would you like to used iterative or recursive to sum?\n");
printf("Enter 1 for iterative or 2 for recursive: ");
scanf("%d\n", &method);
if (method == 1) {
//found in loop.c
sumIterative(stkPtr, numOfIntegers, userInts, sumPnt);
break;
} else if (method == 2) {
//Found in loop.c
sumRecursive(stkPtr, numOfIntegers, userInts, sumPnt);
break;
} else {
printf("Invalid choice. Repeating... \n");
continue;
}
}
printf("Your sum is: %d", *sumPnt);
return 0;
}
Replace scanf("%d\n", &userInts[i]);
with scanf("%d", &userInts[i]);
See this about entering a nonwhitespace character in format specifier in scanf.
It says:
Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments