Monday, May 24, 2010

C program using a function?

I need to create a function that creates a text file. Have the user enter text one line at a time into the text file, and stop only when he types “the end”. I have this so far, what do i need to do finish it?





#include %26lt;stdio.h%26gt;


int main()


{


FILE *fout = fopen("out.txt", "w");


char sentence[100];





if(fout == NULL) {


printf("Error opening file\n");





return 0;


}





printf("Enter a sentence : ");


while(scanf("%s", sentence) != EOF)


fprintf(fout, "%s", sentence);


fclose(fout);


return 0;


}

C program using a function?
Hi tbwada,





essentially, you need to modify your while loop condition to compare the sentence value with "the end":





strcmp(sentence, "the end")





this will return a zero if a match has been found. I haven't compiled this, but I think it should what you want:





#include %26lt;stdio.h%26gt;


int main()


{


FILE *fout = fopen("out.txt", "w");


char sentence[100]="";





if(fout == NULL) {


printf("Error opening file\n");





return 0;


}





printf("Enter a sentence : ");








do


{


fprintf(fout, "%s", sentence);


scanf("%s", sentence);


}


while ( (strcmp(sentence,"the end")!=0) );





fclose(fout);


return 0;


}





note: the fprintf and the scan are reversed so that when you do type "the end" it's not printed to the file.
Reply:try this:


#include%26lt;iostream.h%26gt;


#include%26lt;string.h%26gt;


#include%26lt;stdio.h%26gt;


int main()


{


char sentence[100];


FILE *fout=fopen("out.txt","w");


if (fout==NULL)


{


printf("Error opening file\n");


return 0;


}


do


{


cin.get(sentence,100);


cin.get();


fprintf(fout, "%s\n", sentence);


}


while(strcmp(sentence,"the end"));


fclose(fout);


}
Reply:inside ur while loop ceck for the sentence


while(...)


{


if(strcmpi(sentence,"the end")==0)


break;


fprintf(fout, "%s", sentence);





}


No comments:

Post a Comment