I'm working on a program for my Intro to C class that requires me to write a program that solves jumble puzzles (you know, those anagram puzzles you see in the newspaper), based on a dictionary text file that my professor gave us. It alphabetizes words from the dictionary, takes in jumbles from a text file (called "jumble.txt"), alphabetizes those, then runs a string compare to find a match. I've got all the code written, but it immediately crashes when I try to run it, and I can't figure out why. I thought maybe the Stackoverflow users might be able to help me out here.
Here's the code I have:
#include <stdio.h>
#include <strings.h>
#define MAX_WORD_LEN 6
#define MAX_NUM_WORDS 30000
typedef struct {
char word[MAX_WORD_LEN+1];
char sort[MAX_WORD_LEN+1];
} jumble_type;
void bubblesort(char letters[], int length);
int main () {
int words, jumbles;
int j, q;
jumble_type list[MAX_NUM_WORDS];
jumble_type list2[MAX_NUM_WORDS];
// Creating file pointers
FILE *ifp;
FILE *ifp2;
//Opens Jumble and dictionary files and reads the info from them
ifp = fopen("jumbledct.txt", "r");
ifp2 = fopen("jumble.txt", "r");
//Assigns the value of "words" to the first line of jumbledct.txt
fscanf(ifp, "%d", words);
//Assigns the value of "jumbles" to the first line of jumble.txt
fscanf(ifp2, "%d", jumbles);
// Reads the words from the dictionary into the "word" section of our
// list structure.
int i;
for (i = 0; i < words; i++){
fscanf(ifp, "%s", &list[i].word);
strcpy(list[i].sort, list[i].word);
bubblesort(list[i].sort, strlen(list[i].sort));
printf("%s\n", list[i].sort);
}
//Reads from Jumble.txt
for (i = 0; i < jumbles; i++){
fscanf (ifp2, "%s", &list2[i].word);
strcpy(list2[i].sort, list2[i].word);
bubblesort(list2[i].sort, strlen(list2[i].sort));
//printf("%s\n", list2[i].sort);
}
for(j=0;j<jumbles; j++){
printf("JUMBLE PUZZLE # %d: %s\n", j+1, list2[j].word);
int x=0;
for (q = 0; q < words; q++){
if(strcmp(list2[j].sort, list[q].sort)==0){
printf("%s\n", list[q].word);
x++;
}
}
if (x == 0){
printf("Sorry, this puzzle has no solutions. \n\n");
}
printf("\n");
}
return 0;
}
void bubblesort(char letters[], int length) {
char temp;
int x, y;
for(x = 0; x < length; x++){
for (y = x; y < length; y++){
if (letters[x] > letters[y]){
temp = letters[y];
letters[y] = letters[x];
letters[x] = temp;
}
}
}
}
Thanks in advance for all your help.
My C is a little rusty, but shouldn't the third argument to the fscanf function be an address (like &words and &jumbles)?
Related
My code is to find line number and then print all element in it but it is throwing garbage value and main thing to do is to seperate front one as x and y respectively plese help me seperate x[] = [60,15,62.....] and y[] = [229,221,59,....]
Dataset is
60,229
15,221
62,59
96,120
16,97
41,290
52,206
...
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *myFile;
myFile = fopen("datasetLR1.txt", "r");
int count=0;
char c;
for (c = getc(myFile); c != EOF; c = getc(myFile)) {
if (c == '\n'){
count = count + 1;
}// Increment count if this character is newline
}
int numberArray[count*2];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < count*2; i++){
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < count*2; i++){
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
After you count the number of lines in the file with your first for loop, you should use rewind(myFile);. This puts you back to the beginning of the file. Without this, you are reading off the end of the file, which is producing the garbage values. Other than that, your code works fine.
You should also look at doing fscanf("%d,%d\n", &x, &y);, which should read off both numbers at once (and the newline) and assign them to x and y respectively. This should simplify your code significantly, however, your code works fine without it.
It seems like I didn't quite understand how the file stream works. My text file right now contains the following integers: 1 10 5 4 2 3 -6, but I would like the program to be able to read any number of integers from the file, should it change.
Apparently I'm not even using the correct functions.
The code I have written is the following:
int main() {
printf("This program stores numbers from numeri.txt into an array.\n\n");
int a[100];
int num;
int count = 0;
FILE* numeri = fopen("numeri.txt", "r");
while (!feof(numeri)) {
num = getw(numeri);
a[count] = num;
if (fgetc(numeri) != ' ')
count++;
}
int i;
for (i = 0; i < count; i++) { printf("%d ", a[i]); }
return 0;
}
I would like it to print out the array with the stored numbers, but all I get is: 540287029 757084960 -1
Can someone help me understand what I did wrong and maybe tell me how to write this kind of code properly?
I have fixed your code based on comments. I used fscanf to read from file and limited the amount of numbers that can be stored in array by checking count < 100 and checking whether fscanf filled exactly one argument.
Also, I checked that whether file could be opened or not, just for safety. If it couldn't be opened, then just print error message and return 1.
int main() {
printf("This program stores numbers from numeri.txt into an array.\n\n");
int a[100] = {0};
int num;
int count = 0;
int i = 0;
FILE* numeri = fopen("numeri.txt", "r");
if (numeri == NULL) {
printf("Can't open file\n");
return 1;
}
while (count < 100 && fscanf(numeri, "%d", &num) == 1) {
a[count++] = num;
}
for (i = 0; i < count; i++) { printf("%d ", a[i]); }
return 0;
}
I have a textfile of numbers written in words, with spaces between like..
zero three five two one .. etc there are 3018 words in total.
This is my code:
#include <stdio.h>
int main(void)
{
int i = 0;
int d = 0;
int j = 0;
char array[9054][5];
char hi[9054];
FILE *in_file;
in_file = fopen("message.txt", "r");
while (!feof(in_file))
{
fscanf(in_file, "%s", array[i]);
i++;
}
printf(array[9049]);
while (1);
return 0;
}
so the 9049th worth in my textfile is the number three.. but when I run this script, it prints "threethreezero"instead?? i thought the fscanf ignored whitespace (spaces) so why does accept another three and zero into this string?
OP figured things out with the help of comments, so here is a cumulative fix.
#include <stdio.h>
int main(void)
{
int i = 0;
int d = 0;
int j = 0;
// Make room for the null character
char array[9054][5+1];
char hi[9054];
FILE *in_file;
in_file = fopen("message.txt", "r");
//check `fscanf()`'s return value rather than using feof()
// Limit input put with 5
while (fscanf(in_file, "%5s", array[i]) == 1);
i++;
}
// Check that code read enough input
if (i >= 9049) {
// Do not use `printf()` on uncontrolled strings that may contain %
fputs(array[9049], stdout);
} else {
puts("Oops");
}
while (1);
return 0;
}
I'd appreciate any help I can get. I'm not sure I completely understand this program. I also get the following errors when I try to run it.
I was also told that on line 15 I was trying to mod a char array. What should I be doing? Thanks for taking a look.
structFinal.c: In function print_part':
structFinal.c:14: error: invalid operands to binary %
structFinal.c: In function main':
structFinal.c:36: error: syntax error before ']' token
#include <stdio.h>
#define NAME_LEN 25
typedef struct {
int number;
char name[NAME_LEN+1];
int on_hand;
} part;
void print_part(part p[], int ind) {
int i;
printf("Whole List\n");
for(i = 0; i< ind; i++)
{
if(p[ind].name % 2 == 0)
printf("Part number: %d\n", p[ind].number);
printf("Part name: %s\n", p[ind].name);
if(p[ind].on_hand < 5)
printf("Quantity on hand: %d\n", p[ind].on_hand);
}
printf("%d\n", p[ind].number);
fgets(p[ind].name,50,fp);
fscanf(fp, "%d", &p[ind].on_hand);
printf("%s\n----%d\n", p[ind].name, p[ind].on_hand);
ind++;
fscanf(fp, "%d", &p[ind].number);
a = fgetc(fp);
} print_part(p[ ] , ind);
fclose(fp);
return 0;
Edit: I just tried this on my Ubuntu machine in Netbeans and it ran. We're suppose to run this in Unix and that's were it fails. I'm lost.
Edit: This is my final file so far. I'm pretty sure this works.
#include <stdio.h>
#define NAME_LEN 25
typedef struct {
int number;
char name[NAME_LEN+1];
int on_hand;
} part;
void print_part(part p[], int ind) {
int i;
printf("Whole List\n");
for(i = 0; i< ind; i++)
{
printf("Part number: %d\n", p[i].number);
printf("Part name: %s\n", p[i].name);
printf("Quantity on hand: %d\n", p[i].on_hand);
}
}
int main() {
/* first try, input only one set and print it */
part p[50];
int ind=0;
FILE *fp;
fp = fopen("structTest.txt", "r");
fscanf(fp, "%d", &p[ind].number);
char a;
a = fgetc(fp); /* extract the return symbol out of input buffer */
while (p[ind].number != 0)
{
while (a != '\n')
{
a = fgetc(fp);
}
printf("%d\n", p[ind].number);
fgets(p[ind].name,50,fp);
fscanf(fp, "%d", &p[ind].on_hand);
printf("%s\n----%d\n", p[ind].name, p[ind].on_hand);
ind++;
fscanf(fp, "%d", &p[ind].number);
a = fgetc(fp);
}
print_part(p , ind);
fclose(fp);
return 0;
}
/*
the code is fixed so it will extact all white spaces after a part number
is typed. the getchar while loop will keep get one character to var a
until a return key is reached
*/
Here you have some character at the end. Notices this ` which doesn't belong there?
if(p[ind].name % 2 == 0)`
And this
print_part(p[ ] , ind);
should be
print_part(p , ind);
p[ind].name is a characters array, you cannot run modulu operation on it.
You can run % on numbers - integers.
What would a logical meaning be of doing module on a string? (char array)
Say you have the array contents of abcde what is abcde % 2?
EDIT:
void print(const int *v, const int size) {
FILE *fpIn;
fpIn = fopen("char-array.txt", "a");
int i;
if (v != 0) {
for (i = 0; i < size; i++) {
printf("%d", (int)v[i]);
fprintf(fpIn, "%d\n", (int)v[i]);
}
perm_count++;
printf("\n");
}
fclose(fpIn);
}
I guess this is a relatively simple question :)
Basically the program is using a permutation algorithm, and printing the output to standard output in the console. I also want to write the content to a file via fprintf I assume. Though I cant seem to get it working. It just prints garbage characters into the first line in the text file and nothing more !
I will paste the code below, and help is much appreciated ! The write to file code is found within the print function.
Thanks,
T.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include <time.h>
clock_t startm, stopm;
#define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define PRINTTIME printf("%2.3f seconds used by the processor.", ((double)stopm- startm)/CLOCKS_PER_SEC);
int perm_count = 0;
void print(const int *v, const int size) {
FILE *fpIn;
fpIn = fopen("char-array.txt", "wb");
int i;
if (v != 0) {
for (i = 0; i < size; i++) {
printf("%d", (char)v[i]);
fprintf(fpIn, "%d", v[i]);
fprintf(fpIn, "\n");
}
perm_count++;
printf("\n");
}
}
void permute(int *v, const int start, const int n) {
int i;
if (start == n-1) {
print(v, n);
}
else {
for (i = start; i < n; i++) {
int tmp = v[i];
v[i] = v[start];
v[start] = tmp;
permute(v, start+1, n);
v[start] = v[i];
v[i] = tmp;
}
}
}
int main() {
int i, x;
printf("Please enter the number of terms: ");
scanf("%d", &x);
int arr[x];
printf("Please enter the terms: ");
for(i = 0; i < x; i++)
scanf("%d", &arr[i]);
START
permute(arr, 0, sizeof(arr)/sizeof(int));
STOP
printf("Permutation Count: %d\n", perm_count);
PRINTTIME
return 0;
}
1. Incorrect access modes in fopen call
You open your file as a binary file: fopen("char-array.txt", "wb");. Don't put b to this string containing access modes if you are going to write formatted strings there. And since you probably want to append new data at the end of the file instead of overwritting them, use a instead of w:
fopen("char-array.txt", "a");
2. Writing to the output buffer, not directly into the file
When you are using functions like fprintf, you don't write directly to the file but to the output buffer. You have to use fflush to write data from the output buffer into the file, or you can just close your file by using fclose function which flushes this buffer automatically.
Just add this line:
fclose(fpIn);
at the end of print function.
3. Incorrect formatting of the output
You should not cast int to char. It will truncate your numbers. And you also have fprintf(fpIn, "\n"); in wrong scope I guess. It could look like this:
for (i = 0; i < size; i++) {
printf("%d ", v[i]);
fprintf(fpIn, "%d ", v[i]);
}
perm_count++;
printf("\n");
fprintf(fpIn, "\n");
Don't waste your time doing programming you don't have to, the use of fprintf is nice but since all you want to do is print the output, you can just print things into the file directly using UNIX built-in commands. Say your program is called wirteoutput then all you have to do is pass the following command when calling it from the shell writeoutput > file.txt. All you would have to use would be the printf function.
If you are curious about this, this is an old function and you can find a detailed description in the original paper The UNIX Operating System. Look at the section called Standard I/O.
You didn't cast to a char (from a int) when you wrote to the file as you did with the screen display. The following will provide the same numbers in the file as you're seeing on screen:
fprintf(fpIn, "%d", (char)v[i]);