Hello,

i need help on how to search for a sentence inside a txt file after opening it and then applying a condition if that sentence was found.

im a beginner so i don't know how.

basically i have written a program that uses system("command>file.txt") to start a command line process and write the output to a file , and what i want is to search for a certain line in the output (an error message for example) and force the program to act upon the condition of it being found.

string sentencetolookup="error connecting to server";
system("command>output.txt");

i want to know how to look for "sentencetolookup" inside the "output.txt" file and if found force the program to stop or return an error message.

any help is appreciated
thanks

you need an ifstream object to open the text file, and a string to receive the strings. Both of these are standard c++ classes in <fstream> and <string> header files. There are hundreds, if not thousands, of examples you can follow to write your program so I am not going to repeat them here. Basically you need to (1) read a line using getline function then (2) compare it to the string you are looing for using the == comparison operator.

you need an ifstream object to open the text file, and a string to receive the strings. Both of these are standard c++ classes in <fstream> and <string> header files. There are hundreds, if not thousands, of examples you can follow to write your program so I am not going to repeat them here. Basically you need to (1) read a line using getline function then (2) compare it to the string you are looing for using the == comparison operator.

thanks, i did view alot of pages talking about ifstream, the best thing i could come up with is read a whole text file , i couldn't find anything on how to read specific lines or read all lines one by one and compare each to a string, all examples showed the use of an array as a buffer to read a txt file instead of a string when i compared an array to a string nothing happened

the whole reason im resorting to txt files is because i couldn't figure out how to obtain any returned results (error or successful completion) by other programs , i am using an exe that renames a computer (netdom) and i have a c++ program that would call that exe using the system() function but i want my program to terminate or loop back to the beginning if the exe file returned an error (like computer account already exists or anything of that sort)

You didn't look hard enough. Didn't you run across the getline() method?

i did look hard enough to find and use the getline() method , and i was able to read the whole txt file, but i didn't know where to go or what to do after that, how to lookup a sentence by searching each line in the txt file and then if it is found, tell my program do this and that

Maybe this will help. Note the title...

in that case can anyone point me to where there is a very detailed tutorial on how to use ifstream ?

in that case can anyone point me to where there is a very detailed tutorial on how to use ifstream ?

I guess I was too subtle. Post your code as the link describes. Very often if we see the code we can figure out what to tell you. So far we're only guessing.

int main()
{
	
		char str[5000];
		char errorline[]="grab this text";
		system("command>output.txt");
                fstream file_op("output.txt",ios::in);
		 while(!file_op.eof())
                 {
                         file_op.getline(str,5000);
                         cout <<str;
                 }  
		 if(str==errorline)
		 {
			 cout<<"\nerror found\n";
			 return 0;
		 }

		 file_op.close();
                 system("pause");
		 return 0;


}

you can see that i can only know how to open the file and read it into str array but i don't know how to search the whole file or a certain line or all lines for a string of text that matches errorline

line 6: do you have a program on your computer called command.exe ? If not then that line of code will do nothing other than get an error message from the operating system that "command not found".

lines 8 and 10: that loop doesn't work right. You need to combine them like this:

while( file_op.getline(str,5000) )
{
    // compare the strings here to see if this line is the one you are looking for
}

line 13: you can not compare two c-style character arrays like that. Use strcpy() to do that if( strcpy(errorline, str) == 0)

line 6: do you have a program on your computer called command.exe ? If not then that line of code will do nothing other than get an error message from the operating system that "command not found".

lines 8 and 10: that loop doesn't work right. You need to combine them like this:

while( file_op.getline(str,5000) )
{
    // compare the strings here to see if this line is the one you are looking for
}

line 13: you can not compare two c-style character arrays like that. Use strcpy() to do that if( strcpy(errorline, str) == 0)

thanks dragon but i tried comparing the strings with a strcmp() function and it won't work

this is what happens, if the txt file was created by the running program this way system("somecommand>output.txt") then comparing the strings with a strcmp() function doesn't work [meaning that when the two compared strings do actually match, the program always decides that they don't match]

but if i created the file myself and typed in it whatever i want to be compared, then strcmp() function would work. :confused:

The code you posted a week ago is obviously not the same code you are using today. So post code (I can't see your monitor very well) and zip up the data file and post it too. stramp is case sensitive so maybe the string that's in the data file is not the same case as the string you want to compare. To do a case-insensive compare you can convert both strings to either upper or lower case before calling strcmp(). Some compilers have a case-insensitive compare function, such as stricmp() in Microsoft compilers and compareNoCase() (or something like that) in some other compilers.

hi dragon, sorry for the late reply

here's my code

char str[5000];
                system("mycommand>output.exe");
	char error[]="the error line to be checked";
	fstream file_op("output.txt",ios::in);

	while( file_op.getline(str,5000) )

	{
		cout<<str<<endl;
		if(strcmp(error,str) == 0)
                                    {
                                          getchar();
                                     }         
	{

the code compiles with no errors and the program runs with no errors , but the issue here is that strcmp(error,str) always returns a value other than zero even if the lines compared match up !

whats confusing is that when i create the output.txt file manually and not by having it created using the system("mycommand>output.exe") function and then type in the the same output i would get from mycommand.exe , the strcmp(error,str) would then detect the matching lines properly!

tanks a lot :)

tanks a lot :)

for what ? :?:

whats confusing is that when i create the output.txt file manually and not by having it created using the system("mycommand>output.exe") function and then type in the the same output i would get from mycommand.exe , the strcmp(error,str) would then detect the matching lines properly!

That indicates the text generated by the system() function is not the same as what you type manually, could be as simple as a space, tab character, or capitalization. Load both files up into Notepad and compare them side-by-side to see what are the differences.

That indicates the text generated by the system() function is not the same as what you type manually, could be as simple as a space, tab character, or capitalization. Load both files up into Notepad and compare them side-by-side to see what are the differences.

although they look identical in notepad , i believe like you said, a space or tab character is added somewhere on each line by the system() function.
i tried removing spaces from the line created by the system() function and then using strcmp() but it still didn't work :/

although they look identical in notepad , i believe like you said, a space or tab character is added somewhere on each line by the system() function.
i tried removing spaces from the line created by the system() function and then using strcmp() but it still didn't work :/

Then that obviously wasn't the problem. What I'd do now is display every character entered in hex just before comparing and, as AD suggests, see if there are differences you can't see.

You also might want to post part of the file.

ok here is something i have tried :

char str[500];
	char error[]="Windows IP Configuration"; //error string to find
	system("ipconfig>output.txt");
	fstream file("output.txt",ios::in);
	
	int i=0,l=1,counter=0;
	
	while( file.getline(str,500) )
	{
	   cout<<"\nLine #"<<l<<":\n\n";

	    while(str[i]==error[i])
	     {
	       cout<<"[ "<<str[i]<<" ]"<<" = "<<"[ "<<error[i]<<" ]\n";	
	       i++;
	       counter++;				
	      }

	     if(strcmp(error,str)==0 || counter==24)
	      {
		cout<<"\nerror found!\n";cin.ignore();
	       }

	      i=0;l++;counter=0;
	  }
          file.close();
          return 0;

and this is the output:

Line #1:


Line #2:

[ W ] = [ W ]
[ i ] = [ i ]
[ n ] = [ n ]
[ d ] = [ d ]
[ o ] = [ o ]
[ w ] = [ w ]
[ s ] = [ s ]
[   ] = [   ]
[ I ] = [ I ]
[ P ] = [ P ]
[   ] = [   ]
[ C ] = [ C ]
[ o ] = [ o ]
[ n ] = [ n ]
[ f ] = [ f ]
[ i ] = [ i ]
[ g ] = [ g ]
[ u ] = [ u ]
[ r ] = [ r ]
[ a ] = [ a ]
[ t ] = [ t ]
[ i ] = [ i ]
[ o ] = [ o ]
[ n ] = [ n ]

error found!

you notice the first line in the file is an empty space
now the reason my error was found in the second line is because of the counter inside the [B]if(!strcmp(error,str)||counter==24)[/B] statement even though you can see how the line and the error string match perfectly, [B]!strcmp(error,str)[/B] still didn't see it O_O

Member Avatar for iamthwee

Maybe you need to change:-

cout<<"\nerror found!\n";cin.ignore();

to

cout<<"\nMatch!\n";cin.ignore();

Or alternatively change:-

if(strcmp(error,str)==0

to

if(strcmp(error,str)==1

The choice is yours.

Maybe you need to change:-

cout<<"\nerror found!\n";cin.ignore();

to

cout<<"\nMatch!\n";cin.ignore();

Or alternatively change:-

if(strcmp(error,str)==0

to

if(strcmp(error,str)==1

The choice is yours.

thanks but i don't think you know what kind of a problem i have because your answer does not relate to it

Member Avatar for iamthwee

I'm sorry if I have misunderstood you. But you have given contradictory examples, so I'm not quite sure what to make of it?

In post #19, you have written:-

if(strcmp(error,str)==0 || counter==24)
{
cout<<"\nerror found!\n";cin.ignore();
}

Which is clearly illogical. Ignoring the second part ||counter ==24 , the If strcmp == 0 you should display the message "string matches", so why are you showing the message "\nerror found?" It doesn't make sense?

In any case, if you insist your logic is correct you should post (attach) a sample of your file you are having the problems with.

>>if(strcmp(error,str)==0 || counter==24)
jamthwee is correct about the error in the above line. It should be if(strcmp(error,str) != 0 || counter==24)

I'm sorry if I have misunderstood you. But you have given contradictory examples, so I'm not quite sure what to make of it?

In post #19, you have written:-

if(strcmp(error,str)==0 || counter==24)
{
cout<<"\nerror found!\n";cin.ignore();
}

Which is clearly illogical. Ignoring the second part ||counter ==24 , the If strcmp == 0 you should display the message "string matches", so why are you showing the message "\nerror found?" It doesn't make sense?

In any case, if you insist your logic is correct you should post (attach) a sample of your file you are having the problems with.

check the parameters being compared in this statement If strcmp(error,str) == 0 !!!!
if the condition is true then str EQUALS error and therefore error is found[/B] NOT [B]AN ERROR IS FOUND[/B] !!
read the entire last code i posted and you will understand what i mean by error !


>>if(strcmp(error,str)==0 || counter==24)
jamthwee is correct about the error in the above line. It should be if(strcmp(error,str) != 0 || counter==24)

no dragon he is not, using != instead is what makes no sense !!!!

replace the word error with another word like line or sentence and check if it still doesn't make any sense to you both

Member Avatar for iamthwee

ok... but have you attached your text file for us to look at like I said?

ok... but have you attached your text file for us to look at like I said?

the txt file is created by this command system("ipconfig>output.txt"); and the string that i wanna look for and is called error is declared here char error[]="Windows IP Configuration"; so this is what the txt file would look like:

Windows IP Configuration


Ethernet adapter Local Area Connection:

        Media State . . . . . . . . . . . : Media disconnected

Ethernet adapter Local Area Connection 3:

        Media State . . . . . . . . . . . : Media disconnected

Ethernet adapter Wireless Network Connection:

        Connection-specific DNS Suffix  . :
        IP Address. . . . . . . . . . . . : 192.168.1.3
        Subnet Mask . . . . . . . . . . . : 255.255.255.0
        Default Gateway . . . . . . . . . : 192.168.1.1

let me post the code and result for you again

char str[500];
	char error[]="Windows IP Configuration"; //error string to find
	system("ipconfig>output.txt");
	fstream file("output.txt",ios::in);
	
	int i=0,l=1,counter=0;
	
	while( file.getline(str,500) )
	{
	   cout<<"\nLine #"<<l<<":\n\n";

	    while(str[i]==error[i])
	     {
	       cout<<"[ "<<str[i]<<" ]"<<" = "<<"[ "<<error[i]<<" ]\n";	
	       i++;
	       counter++;				
	      }

	     if(strcmp(error,str)==0 || counter==24)
	      {
		cout<<"\nerror found!\n";cin.ignore();
	       }

	      i=0;l++;counter=0;
	  }
          file.close();
          return 0;

and the result you get is this:

Line #1:


Line #2:

[ W ] = [ W ]
[ i ] = [ i ]
[ n ] = [ n ]
[ d ] = [ d ]
[ o ] = [ o ]
[ w ] = [ w ]
[ s ] = [ s ]
[   ] = [   ]
[ I ] = [ I ]
[ P ] = [ P ]
[   ] = [   ]
[ C ] = [ C ]
[ o ] = [ o ]
[ n ] = [ n ]
[ f ] = [ f ]
[ i ] = [ i ]
[ g ] = [ g ]
[ u ] = [ u ]
[ r ] = [ r ]
[ a ] = [ a ]
[ t ] = [ t ]
[ i ] = [ i ]
[ o ] = [ o ]
[ n ] = [ n ]

error found!

and like i said before , the strcmp() function will fail to detect any matching between the two strings and only the counter is going to set a condition to detect it

Member Avatar for iamthwee

Yes, but you need to post your actual text file (the one that doesn't do the strcmp properly) so we can at least try to duplicate what you are experiencing our end.

I would also like to analyse the text file with a hex editor to see if there are any hidden characters.

Member Avatar for iamthwee

I see your point...

Member Avatar for iamthwee

I can only assume that system dump is adding something to the end of the lines. Like appending an unknown character(s) or something.

Try and go through the output.txt with a hex editor... I have to go, maybe someone who has used ipconfig can help you. It might be something simple I have overloooked.

im not good with reading hex, but checking the code i posted you can see that both line do match and still the strcmp() wont detect it

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.