I know that the programming style is bad/functions NOT being used are terrible...
But I cannot escape my professor's methods...

Ok. So this program is meant to read a text file containing:

Have a good day

then we pick a pick a word, and change it, and output it to the second textfile.

I have done all this, but my textfile output is:
Have a vÿÿÿ day

after I decide to change the word to bad.
I'm just wondering how I can fix this...

Style is so bad and terrible but this is just a Logic & intro course...

#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include <ctype.h>

main()
{

	//input file
	FILE * file;
	
	//ouput file
	FILE * pFile = NULL;

	//String arrays
	char sent [120];
	char change [120];
	char temp [120];
	char replace [120];
	char output_sentence [120];
	 // char *filename = "";

	//for loops
	int  x, y;
	
	file = fopen("C:\\input.txt", "r");
	  pFile = fopen("66file.txt", "w");

	
	// this stores the text from the file into the array called sent
	fgets (sent , 120 , file);
	puts (sent);
	fclose (file);

	printf("Which word would you like to change?:\n");
	gets(change);

	printf("Change word to?:\n");
	gets(replace);

	for  (x = 0; sent[x] !='\0'; x++)
	{
		if  ((sent[x] == change[0]) && ((sent[x-1] == ' ') || (x==0)))
		{
			for (y=0; ((sent[x] !=' ') && (sent[x] !='\0') && (0==ispunct (sent[x])));y++,x++)
			{
				temp[y] = sent[x];
			}
			temp[y]='\0';

			if (strcmp(change,temp) == 0)
			{
				output_sentence[x] = replace[x];
				printf("%s", &replace);
			}
            

		}
	    output_sentence[x] = sent[x];
		printf("%c",sent[x]);

	}
	for(;x == 119;x++)
    {
           output_sentence[x] == ' ';
    }
   fputs (output_sentence,pFile);
   fclose (pFile);

	scanf(" ");
	return 0;
}

Probably ancillary to your stated problem, but what do you do when x is 0 in the following (sent[x-1] == ' ') ? You are probably looking for ((x == 0) || (sent[x-1] == ' ')) You probably also want to look at line 64. Perhaps x < 120 would make a better choice?

And one other thing, avoid gets at all costs. It is a security issue and, while it probably wont affect you here, it's best not to establish bad habits early.

Edited 5 Years Ago by L7Sqr: n/a

This article has been dead for over six months. Start a new discussion instead.