- #1
Bob Busby
- 47
- 0
Homework Statement
I have to write a program that takes in a file that looks like this:
3424: 313
4334: 543
etc.
and sorts the numbers on the write. Everything for getting the file into an array was done for me so I know it's correct. I'm having two strange problems. First, whenever I'm checking user input for choosing which algorithm to use, my "Try again message is always printed twice. I traced it and inexplicably the while loop always goes through twice.
Second, the sort works fine but every time it's time for the program to finish the console window errors out and says "blah.exe has stopped working."
Homework Equations
Code:
This program loads, sorts in decending order, and prints 100 numbers. */
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
void swap(int *x, int *y);
int arrLen(int *arr);
char menu();
void bubbleSort(int *arr);
int main(int argc, char *argv[]) {
int Nums[100];
int NumNums, N;
char ans;
if (argc != 2) {
printf("usage: ./P1-2 valuefile\n");
exit(1);
}
NumNums = Load_Mem(*++argv, Nums);
if (NumNums != 100) {
printf("valuefiles must contain 100 entries\n");
exit(1);
}
/* Your program goes here */
ans = menu();
bubbleSort(Nums);
for(N = 0; N < NumNums; N++) /* don't change this print loop */
printf("%4d: %8d\n", N, Nums[N]);
//ans = getchar();
return 0;
}
/* Swaps two ints in an array */
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int arrLen(int *arr)
{
int i = 0;
while(*(arr++)) i++;
return i;
}
char menu()
{
int i;
char c = ' ';
for(i = 0; i < 50; i++) printf("-");
printf("\nChoose your preferred sorting method:\n");
printf(" 'b' - Bubble Sort\n");
printf(" 'q' - Quick Sort\n");
do {
c = getchar();
printf("Try again\n");
} while(c != 'b' && c != 'q');
return c;
}
/* Performs a version of bubble sort */
void bubbleSort(int *arr)
{
int i, j, len, n, swapped = TRUE;
len = arrLen(arr);
n = len;
while(swapped)
{
swapped = FALSE;
for(j = 0; j < len-1; j++)
{
if(arr[j] > arr[j+1])
{
swap(&arr[j],&arr[j+1]);
swapped = TRUE;
}
}
}
}
/* This routine loads in up to 100 newline delimited integers from
a named file in the local directory. The values are placed in the passed integer array. The number of input integers is returned. */
int Load_Mem(char *InputFileName, int IntArray[]) {
int N, Addr, Value, NumVals;
FILE *FP;
FP = fopen(InputFileName, "r");
if (FP == NULL) {
printf("%s could not be opened; check the filename\n", InputFileName);
return 0;
} else {
for (N=0; N < 100; N++) {
NumVals = fscanf(FP, "%d: %d", &Addr, &Value);
if (NumVals == 2)
IntArray[N] = Value;
else
break;
}
fclose(FP);
return N;
}
}
The Attempt at a Solution
I've tried tracing through it with gdb and two different IDE's but with no luck. Any help you can offer will be much appreciated!