help with making pFile stops

hey there,thanks for everyone that helped me till now, even though i was not registered :P

i have a problem with making pFile stops
im putting the sentences but i dont know how to stop it, the file should be called "q3.txt".
and i need to writie "finish" to stop putting sentences

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

void main()
{
	char* finish;
	FILE * pFile;
	char sentence[256];

	cout << "Enter a sentence\n";
	cin.getline(sentence, 256, 5);
	while (sentence!=finish)
	{
		pFile = fopen("q3.txt", "a");
		fputs(sentence, pFile);
		fclose(pFile);
	}
}


it should look like that:

Enter sentences . To finish press Finish
My name is Hilla
What is your name?
Yuval
Finish

Your sentences are:
My name is Hilla
What is your name?
Yuval
Finish
Press any key to continue . . .

inside the txt file, should be like that:
My name is Hilla
What is your name?
Yuval
Finish
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main() //< It should be int main()
{
	FILE * pFile;
	char sentence[256];

	cout << "Enter a sentence\n";
	cin.getline(sentence, 256, 5);
	while (sentence != "finish") //< You mean that?
	{
		pFile = fopen("q3.txt", "a");
		fputs(sentence, pFile);
		fclose(pFile);
	}

        return 0;
}
Last edited on
while (sentence!=finish)
This compares the address of the sentence array with the (uninitialized) pointer finish. Unless you execute finish = sentence somewhere, they won't be equal.

while (sentence != "finish")
This compares the address of the sentence array with the array of the constant string "finish". They will never be equal.

What you want to do is compare the contents of the sentence array, not the address. For that you need strcmp:
while (strcmp(sentence, "finish") != 0)

strcmp returns a value less than, equal to, or greater than 0 depending on whether the first argument is, respectively, lexographically less than, equal to, or greater than the second argument.

Since strcmp() 0 when strings are equal and this is contrary to the usual "0 is false) meaning, I always code it with an explicit comparison to zero. To me, this makes the code easier to read.
Topic archived. No new replies allowed.