Member Avatar for anu07

I have a little problem with strcmp here,the following code basically opens a file and writes to it until I enter "\esc",at which point the program should stop....but the problem is,it does not,and I can't figure out what might be the prob.Thanks for your time(I am using turbo c++ 3.0 as a compiler).

#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<stdio.h>


void main()
{
	char exit[4]="\esc";
	ofstream myfile;
	myfile.open("chk.txt",ios::ate);
	cout<<"write to file\n";

	while(1)
	{
		char temp[600];
		gets(temp);
		[B]if(strcmp(temp,exit))
			break;[/B]
		myfile<<temp<<endl;
	}

	myfile.close();
}

Recommended Answers

All 7 Replies

Hello anu07,
strcmp wil return value 0 if both the strings are equal.You should check whether strcmp(temp,exit)==0. If you give if(strcmp(temp,exit)) it will break at the first time itself.

Member Avatar for anu07

Thanks,but now there is another problem,if I do as you say,even after entering "\esc" it doesn't break,it carries on.

You should give double slash in the array exit because single slash is used for giving '\n','\r' etc.

char exit[4]="\\esc";

"\\esc" implies that your string is \esc.

Member Avatar for anu07

done that,no difference :(

What did you give in runtime? \esc or \\esc?
because it works in mine.

Member Avatar for anu07

okk I forgot to change from temp[4] to temp[5]...thanks a lot...:)

Member Avatar for anu07

okk I forgot to change from temp[4] to temp[5]...thanks a lot...:)

I meant exit[4] to exit[5]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.