GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 15-Jul-2006, 13:33
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: Sweden
Posts: 137
aijazbaig1 has a spectacular aura about
Question

Menu of character strings


Hello.
I am trying to write a simple program which accepts input string from the user and compares the scanned string to each string in an array of character strings. For the time being, I assume that the input string,just as the strings in the defined array, has just single spaces between the words so that I can leave that checking to a later part.
So the scanned string is compared to each of those strings, a message is sent to the user telling him what he wrote ( ..i know you may be thinking whats the use of letting the user know what he just typed a moment ago...but thats not the point here, I will be writing sample functions for each of these choices later on but for the moment I am just checking the comparison part and it is not working the way i want it to work ..though the syntax seems to be right i suppose).
Heres my program:

CPP / C++ / C Code:
#include <stdio.h>
#include <string.h>

int main()
{
	const char *idioms[] = {"create array","free memory",
							 "find smallest","check for palindrome"};
	char string1[50];
	int i=0,flag,equal;
	printf("enter the string\n");
	scanf("%s",string1);
	printf("\n\n");
	i=0;
	do
	{
		equal = (_strnicmp(idioms[i],string1,strlen(idioms[i])+1));
		if(equal==0)
		{
			printf("you opted for %s\n",string1);
			flag = !equal;
		};
		++i;
	}
	while(flag || i>3);
}

I doubt if the size_t type has got something to do with it but still...my program is just too simple at this stage but it still wont work

Ive tried entering the string exactly as the strings in the array above(each once at a time ofcourse) but it still wont print the statement which it should. I wonder why the comparison is never showing the equality between the strings. Has it got to do something with the locale (I hardly know what a locale is so I would be pleased if someone would also throw some light on it.. )

Looking to hear from you,
Best Regards,
Aijaz Baig.
Last edited by aijazbaig1 : 15-Jul-2006 at 13:41. Reason: change the title
  #2  
Old 15-Jul-2006, 13:42
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,245
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: Menu of character strings


If you print your string right after your input, you'll notice what was actually read. Whitespace stops a scanf() read. Also Check this out and follow the gets() link for a solution.

You also need a return at the end of main()
__________________

Age is unimportant -- except in cheese
  #3  
Old 15-Jul-2006, 16:29
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: Sweden
Posts: 137
aijazbaig1 has a spectacular aura about
Question

Re: Menu of character strings


Hi.
Thanks for letting me know that I cannot read a white space with a scanf. I did allot a lot of space but i didn't knew that I could instead use the fgets which reads a specified number of characters or till the 1st newline character(whatever comes first) and appends a NULL after that isnt it? And this time I am printing the string using the array *idiom as it shouldn't really matter because the comparison would yield an output of zero if and only if both the arguments of the _strnicmp function have the same characters, though the case may be different.

So heres the modified code and it works just fine but I think there is a problem with regards to memory initialization and hence after displaying the output it becomes non responsive and I see a pop-up window displayed by the OS I guess,informing me that the 'filename'.exe file has become non-responsive and asking me if i'd like to report this to microsoft..you know what I mean here, don't u?
heres whats written in the title bar of that window:
"array_menu.exe has encountered a problem and needs to close. We are sorry for the inconvenience."

and heres the C code that caused windows to encounter that problem :
CPP / C++ / C Code:
#include <stdio.h>
#include <string.h>

int main()
{
	const char *idioms[] = {"create array","free memory",
							 "find smallest","check for palindrome"};
	char string1[50];
	int i=0,flag,equal;
	for (i=0;i<=3;i++)
		printf("the size of string %d is %d\n",i,strlen(idioms[i]));
	printf("enter the string\n");
	fgets(string1,50,stdin);
	if (string1[strlen(string1)-1] == '\n') string1[strlen(string1)-1] = '\0';
	printf("\n\n");
	i=0;
	do
	{
		equal = (_strnicmp(idioms[i],string1,strlen(idioms[i])+1));
		if(equal==0)
		{
			printf("you opted for entry number %d , %s \n",i,idioms[i]);
			flag = !equal;
		};
		++i;
	}
	while(flag || i>3);
}

I hope you might have understood the pop up windows that I was referring to. After all, we've all had our days with Windows, haven't we?
  #4  
Old 15-Jul-2006, 19:10
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,720
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Menu of character strings


Quote:
Originally Posted by aijazbaig1
Hi.
nt.

So heres the modified code and it works just fine but I think there is a problem with regards to memory initialization and hence after displaying the output it becomes non responsive

I don't understand how it you could could say that it "works just fine", given the behavior you describe.

Maybe you could look at the conditions for exiting the do{}while() loop.

Or, you could make the program tell you what it is doing:

CPP / C++ / C Code:
    do
    {
        printf("In the do{} while() loop: i = %d, flag = %d\n", i, flag);
        equal = (_strnicmp(idioms[i],string1,strlen(idioms[i])+1));
        if(equal==0)
        {
            printf("you opted for entry number %d , %s \n",i,idioms[i]);
            flag = !equal;
        };
        ++i;
    }
    while(flag || i>3);

Regards,

Dave
  #5  
Old 16-Jul-2006, 00:18
orochimaruSanin orochimaruSanin is offline
New Member
 
Join Date: Jun 2006
Posts: 15
orochimaruSanin is on a distinguished road

Re: Menu of character strings


Mr. aijazbaig1 maybe this is wat you are looking for :

CPP / C++ / C Code:
#include <stdio.h>
#include <string.h>
const int BUFFERSIZE = 255;

int main()
{
	const char *idioms[] = {"create array","free memory","find smallest","check for palindrome"};
	char buffer[BUFFERSIZE];
	int i=0,flag = 0,equal = -1;
	char choice;


	do
	{
		fflush (stdin);
        fputs("Enter the string: ", stdout);
        fgets(buffer, BUFFERSIZE, stdin);
        i = 0;
        do
        {
            equal = strncmp (idioms[i], buffer, strlen (idioms[i]));
            if(equal==0)
			{
                printf("Match Found. You opted for entry number %d which is \"%s\". \n", i, idioms[i]);
                flag = !equal;
			}
            ++i;
		}
        while(!flag && i <= 3);

        if (flag == 0)			// no matching entries found
            fputs ("\nThe input string didnt match any of the entries !", stdout);

		fflush (stdin);
		fputs ("\n\nDo u want to continue? ", stdout);
		scanf ("%c", &choice);
	}
	while (choice != 'n' && choice != 'N');

    getchar ();
    return 0;
}

Hope this helps. In case of doubts do post again.

Regards,
Orochimaru...
  #6  
Old 16-Jul-2006, 01:13
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: Sweden
Posts: 137
aijazbaig1 has a spectacular aura about
Question

Re: Menu of character strings


Hello there.
I finally got the problem. My test condition in the do while loop was wrong. It should instead have been !flag as correctly pointed out by orochimaruSanin.

Additionally, the bit-wise and operator which you have used is incorrect as I want to exit the loop as soon as a match is found or after all the elements have been compared implying that there was no match. Furthermore, one should never forget to replace the newline character appended to the string by fgets by the NULL character .

Heres the modified program. This time I have used a choice variable to check if the user wants to continue but it does 3 things wrong.
1: It doesn't actually respond to what the user is entering as his choice. Even if I enter a n or a N or even if I just press the enter key it just keeps looping and continues to search for a match. Seems to be stuck in an infinite loop.
2: For all strings entered except the 1st i.e. "create array", it cannot find a match.
3: When a match is not found it doesn't display whats it supposed to be displaying i.e. "The input string didnt match any of the entries !".

Heres the modified program:
CPP / C++ / C Code:
#include <stdio.h>
#include <string.h>

int main()
{
	const char *idioms[] = {"create array","free memory",
							 "find smallest","check for palindrome"};
	char string1[50],choice;
	int i=0,flag,equal;
	do
	{
		fflush(stdin);
		printf("enter the string\n");
		fgets(string1,50,stdin);
		if (string1[strlen(string1)-1] == '\n') string1[strlen(string1)-1] = '\0';
		printf("\n\n");
		i=0;
		do
		{
			equal = (_strnicmp(idioms[i],string1,strlen(idioms[i])+1));
			if(equal==0)
				{
				printf("you opted for entry number %d , %s \n",i,idioms[i]);
				flag = !equal;
				};
			++i;
		}
		while(!flag || i>3);
		if (flag == 0)  // no matching entries found
			fputs ("\nThe input string didnt match any of the entries !", stdout);
		fflush (stdin);
		fputs ("\n\nDo u want to continue?\n", stdout);
		scanf ("%c", &choice);
	}
	while(choice != 'n' || choice != 'N');
	return 0;
}
Heres a sample output from the program:
Code:
enter the string create array you opted for entry number 0 , create array Do u want to continue? N enter the string free memory Do u want to continue? enter the string create array you opted for entry number 0 , create array Do u want to continue?


What do you thing am I overlooking? Please do let me know.

Would someone explain the use of the the fflush function here?. Do we need to have such a function everytime we make a call to fgets if we want to read the characters right from the beginning of the stream for every new string entered and not from the last time where fgets stopped? So does it serve that purpose by flushing the input stream so that a new set of characters could be entered?
Please do elaborate.

Best Regards,
Aijaz Baig.
  #7  
Old 16-Jul-2006, 02:57
orochimaruSanin orochimaruSanin is offline
New Member
 
Join Date: Jun 2006
Posts: 15
orochimaruSanin is on a distinguished road

Re: Menu of character strings


Looks like you didnt copy paste my code and then run it coz its working fine on my system.

Still i evaluated your program and found some problems :

Quote:
Additionally, the bit-wise and operator which you have used is incorrect

Well actually no, its not wrong its correct. This is coz if you use the condition
CPP / C++ / C Code:
 while ( choice != 'n' || choice != 'N' ) 
and if you enter 'n' the first condition evaluates to FALSE but the second condition evaluates to TRUE since 'n' != 'N' .

and FALSE || TRUE = TRUE and hence the loop keeps on going on and on.

where as if you use AND operator

FALSE && TRUE = FALSE which is wat we want.

Quote:
Furthermore, one should never forget to replace the newline character appended to the string by fgets by the NULL character

Correct me if i am mistaken but i think that fgets () automatically appends a NULL termination at the end of the received string so you need not do it.

Quote:
Would someone explain the use of the the fflush function here?.

The fflush () function flushes the stream which is provided as an input to it. So by doing fflush (stdin) i flush the input stream so that the stray input left over from the prev attempts does not interrupt with the current input session.

And atlast the code snippet which caused your program to not work properly is
CPP / C++ / C Code:
 equal = (_strnicmp(idioms[i],string1,strlen(idioms[i])+1)); 

which should be

CPP / C++ / C Code:
 equal = (_strnicmp(idioms[i],string1,strlen(idioms[i])); 

since in the prev stmt u end up adding 1 to the string array which causes malfinction.

Also this code piece is wrong :

CPP / C++ / C Code:
do
   {
....
    }
 while(!flag || i>3); // this is wrong

it should be

CPP / C++ / C Code:
do
   {
....
    }
 while( !flag  &&  i <= 3); // since we should bail out even if any one fails


Hope this explanation helped.
If this caused your program to work please post your feedback so thta other ppl can benefit from this.
Bye.

Regards,
Orochimaru...
  #8  
Old 16-Jul-2006, 03:00
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,245
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: Menu of character strings


You took suggestions from a new programmer that gave you very bad information.
CPP / C++ / C Code:
fflush(stdin);
Again, check out why. You too, orochimaruSanin


You might want to define a value for the number of idiom entries. What you have is called a hard coded value. If you need to change things, you have to find all the 3's and change them, and you might miss one, or change a wrong one by mistake. So define the value with something like
CPP / C++ / C Code:
#define NUM_IDIOM  3
Now you can change the number every place it's used in one shot. You won't miss one this way.


CPP / C++ / C Code:
scanf ("%c", &choice);
Check this. While you're at it, you might as well look at all the scanf() tutorials, starting here. You may decide to drop the function in the trash where it belongs


Quote:
Originally Posted by aijazbaig1
1: It doesn't actually respond to what the user is entering as his choice. Even if I enter a n or a N or even if I just press the enter key it just keeps looping and continues to search for a match. Seems to be stuck in an infinite loop.
CPP / C++ / C Code:
while (choice != 'n' || choice != 'N');
Let's assume you entered 'n'. This comparison says if choice != 'n' which is FALSE, then if choice != 'N' which is TRUE. TRUE || FALSE is always TRUE. You want &&, not ||.

One way to check this type of if yourself is just before the test add:
CPP / C++ / C Code:
printf("n=%d  N=%d  n||N=%d \n", (choice != 'n'), (choice != 'N'), 
                                 (choice != 'n' || choice != 'N'));


Quote:
Originally Posted by aijazbaig1
2: For all strings entered except the 1st i.e. "create array", it cannot find a match.
I don't see the problem... yet.


Quote:
Originally Posted by aijazbaig1
3: When a match is not found it doesn't display whats it supposed to be displaying i.e. "The input string didnt match any of the entries !".
I don't see the problem either... yet. It's probably the way you deal with equal and flag. If I may suggest an easier way to deal with this loop:
CPP / C++ / C Code:
for (i = 0; i < NUM_IDIOM; i++)
{
    if (_strnicmp(idioms[i],string1,strlen(idioms[i])+1) == 0)  
    {                       // TRUE will execute this code
        printf("you opted for entry number %d , %s \n",i,idioms[i]);
        break;              // exit the loop
    }
    // after the loop, if i < NUM_IDIOM, a match was found.

    if (i >= NUM_IDIOM)     // no matching entries found
    {                       // always use braces around an IF
        fputs ("\nThe input string didnt match any of the entries !", stdout);
    }


Quote:
Originally Posted by aijazbaig1
Would someone explain the use of the the fflush function here?.
Sure. Bad programming practice, bad instructor that teaches errors, compiler that doesn't follow the standard. In other words, a bad use of the function as explained above.

Quote:
Originally Posted by aijazbaig1
Do we need to have such a function everytime we make a call to fgets if we want to read the characters right from the beginning of the stream for every new string entered and not from the last time where fgets stopped?
No. People use this fflush() statement because when they use other input function like scanf(), getchar(), and other ill-behaved functions, the input stream is left with junk in it. fgets() solves most of these problems.


Quote:
Originally Posted by orochimaruSanin
Correct me if i am mistaken but i think that fgets () automatically appends a NULL termination at the end of the received string so you need not do it.
Please look at the code he used:
CPP / C++ / C Code:
if (string1[strlen(string1)-1] == '\n') 
{
    string1[strlen(string1)-1] = '\0';
}
IOW, if the last character is '\n', change it to '\0'. He's doing this to make sure he can compare properly.


Quote:
Originally Posted by orochimaruSanin
The fflush () function flushes the stream which is provided as an input to it. So by doing fflush (stdin) i flush the input stream so that the stray input left over from the prev attempts does not interrupt with the current input session.
No it doesn't -- technically. See the post I pointed out.


Quote:
Originally Posted by orochimaruSanin
And atlast the code snippet which caused your program to not work properly is
CPP / C++ / C Code:
 equal = (_strnicmp(idioms[i],string1,strlen(idioms[i])+1)); 
which should be
CPP / C++ / C Code:
 equal = (_strnicmp(idioms[i],string1,strlen(idioms[i])); 
since in the prev stmt u end up adding 1 to the string array which causes malfinction.
Good catch. I missed that....

Also, please take another look at the Guidelines, #2F.
__________________

Age is unimportant -- except in cheese
  #9  
Old 16-Jul-2006, 05:05
orochimaruSanin orochimaruSanin is offline
New Member
 
Join Date: Jun 2006
Posts: 15
orochimaruSanin is on a distinguished road

Re: Menu of character strings


Thanks Mr. WaltP for pointing out such silly mistakes to me and my friend. I would be careful while using scanf () and fflush () in the near future and i have read the links posted by you. Keep up the good work. Thanks.

Regards,
Orochimaru...
  #10  
Old 17-Jul-2006, 01:39
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: Sweden
Posts: 137
aijazbaig1 has a spectacular aura about
Question

Re: Menu of character strings


Hello there.
Thanks for the wonderful feedback Walt. I was suprised how sometimes somethings just won't behave the way you want or expect them to, making u scratch your head looking for logical reasons.

This time I scanned and rescanned my program looking for some goofs which I thought may have caused the program to malfunction. I made quite a few corrections and I was able to make the program work to some extent. I still have some problems though which I have tried my best to put forth in a simple language.

The program works fine during when the outer do-while loop is being executed the first time. It then asks me if I'd like to continue the program. If I enter anything other than a 'n' or a 'N' ,what happens is that it asks me for the string but it doesn't wait for me to enter it again and it keeps on asking the same question again and again whether Id like to continue or not until I enter a 'N' or a 'n'.
If you haven't followed what I am talking about here, I am soon going to follow this with the modified program and the various outputs it is generating for various cases.

CPP / C++ / C Code:
#include <stdio.h>
#include <string.h>

int main()
{
	const char *idioms[] = {"create array","free memory",
							 "find smallest","check for palindrome"};
	char choice;
	int i=0,flag=0,equal;
	do
	{
		char string1[100] = {0};
		printf("enter the string\n");
		fgets(string1,100,stdin);
		if (string1[strlen(string1)-1] == '\n') string1[strlen(string1)-1] = '\0';
		printf("\n\n");
		i=0;
		do
		{
			equal = (_strnicmp(idioms[i],string1,strlen(idioms[i])));
			if(equal==0)
				{
				printf("you opted for entry number %d , %s \n",i,idioms[i]);
				flag = !equal;//flag indicates that a match was found.
				};
			++i;
		}
		while(!flag && i<=3);
		if (flag == 0)  // no matching entries found
			fputs ("\nThe input string didnt match any of the entries!\n\n", stdout);
		fputs("do u wish to continue?\n",stdout);
		choice = getchar();
	}
	while(choice != 'n' && choice != 'N');
	return 0;
}

Say if I enter 'check for palindrome' and I indicate that I would like to continue then heres what I see on my console:
Code:
enter the string check for palindrome you opted for entry number 3 , check for palindrome do u wish to continue? y enter the string do u wish to continue? n Press any key to continue
As you can see, if it not waiting for any input from the user until it asks the same question again. It only responds to a n in that the program quits properly.

Heres the sample output if I enter anything to generate a mismatch.
Code:
enter the string sdnfsnfddf The input string didnt match any of the entries! do u wish to continue? y enter the string The input string didnt match any of the entries! do u wish to continue? n Press any key to continue
As you can see, somehow the compiler tends to remember the contents of string1. To counter that I added a line of code to define and initialize all values of string1 to zero each time the outer do while loop is executed.

But we cannot directly jump to the conclusion that it is remembering the contents of string1 because it is behaving differently when a match is found. As can be seen for the case when I entered 'check for palindrome' for the first time and I indicated that I wished to continue, it didn't repeat the message "you opted for entry number %d, %s\n........."

This is in contrast with the case when a match wasn't found wherein it kept on repeating the message "The input string didnt match any of the entries!" after the 1st execution of the outer do-while loop.
Has it got to do anything with the stream here?
I hope that I have been simple and clear enough to put my problem so that you may have understood what I meant here. In addition i would like to inform you that I am using VC++ version 6, just in case if that might help you in diagnosing the problem.

Hope to hear from you soon,

Best Regards,
Aijaz.
 
 

Recent GIDBlogDeveloping GUIs with wxPython (Part 4) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Read a .html file, check that file for links salemite C Programming Language 10 17-Jan-2008 07:56
Shapes Functions Version 2 - Arrays! Cecil C Programming Language 1 09-Jul-2006 20:39
Need help with strings sasukekun C++ Forum 4 24-Apr-2006 10:51
variables return to previous value after i try to set them nasaiya MS Visual C++ / MFC Forum 2 14-Jun-2005 00:43
Help wit my source code compiler errors Krandygrl00 C++ Forum 1 06-Jun-2005 08:14

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 20:20.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.