3

I'm a beginner in C and trying to create a program and having a problem with my main function.

Problem:

  1. 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.

  2. 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 = &sum;

  //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;
}
unwind
  • 391,730
  • 64
  • 469
  • 606
Abushawish
  • 1,466
  • 3
  • 20
  • 35

3 Answers3

2

Problem 1:

Just replace :

scanf("%d\n", &userInts[i]);

by scanf("%d", &userInts[i]);

2

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.

HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33
1

And add fflush(stdout) after all printf statements where the format string doesn't end with \n. Otherwise the output will be displayed only after the next \n is output.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115