StrCmp Char,Literal String in an if statement

Hi, I am new to c++ programming and trying to make a few test programs to increase my knowledge, I spend four hours researching this one function last night and can not seem to get it working, so obviously I am missing something, I was hoping someone here could correct me on my syntax.

Following is my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
char buffer[256];
ifstream myfile ("test.txt");
while (! myfile.eof() )
{
myfile.getline (buffer,100);
 cout << buffer << endl;
}

	if(strcmp(buffer,"My Test Phrase/n") == 0)
	{
		//do stuff
        }
        else  cout << "Sorry, didn't work" << endl;


Now, the file input method works fine, it will read line by line (this file only has one line anyway). However I can not get the strings to register a match, and yes I have verified Case.

Thank you in advance for help for this beginner!


EDIT* SOLVED
Finally after 10 hours of sleep, I figured it out. The problem wasn't with strcmp, it was with the program writing the text file. It was writing more than one character for /endline, I fixed it. And it works great now.
Last edited on
Shouldn't the if statement be inside the loop?
I think you meant "\n", not "/n".

PS: I might be wrong, but I think the getline function does not add the newline characters at the end of the string. Instead, it appends a null character. Try without any \n. Or maybe not...
Last edited on
@Ramses12
I've tried it without the newline character, however I haven't tried \n. I shall do so.

@Peter87
It would if the text file had multiple lines, atm it only has one.
Last edited on
Try change the loop to this:
1
2
3
4
while (myfile.getline(buffer,100))
{
	cout << buffer << endl;
}

\n Does not seem to work either.
I have to ask this because I am so new to the syntax.
Is my declaration of 'char buffer[256]' causing additional NULL characters at the end or is that only specifying the MAX number of characters allowed in the stream?
Also, comparing it to a literal string do I have to account for the NULL somewhere?
"My Test Phrase" + NULL

Thank you.
@Peter87
The file reading loop works fine, output to cout is all correct, it's the IF statement that doesn't register.
In that case it should work if you have removed /n
It did thanks, in the op I posted what was wrong!
Topic archived. No new replies allowed.