General discussion

Locked

Basic C loop

By mckay_w ·
LEARNER C PROGRAMMER
I am trying to use either a 'while' or a 'do-while' loop using a string, but it doesnt want to work, could someone please help me.

THESE ARE THE BITS OF CODE THAT IS AFFECTED.

char Description[100];

while (Description != "zzz")
{
printf("Enter Description: ");
scanf(" %s", Description);
....
}

This conversation is currently closed to new comments.

8 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

Basic C loop

by gerMusic In reply to Basic C loop

scanf("%s",&Description);

Scanf requires a pointer to the adres of the
variable (const char*).

Check with debugger: Description will never have
the value you've typed

Collapse -

Basic C loop

by mckay_w In reply to Basic C loop

The question was auto-closed by TechRepublic

Collapse -

Basic C loop

by jeng In reply to Basic C loop

In addition, when comparing strings in C, you're actually comparing an array of characters. You will need a function, strcmp(), to do such a comparison. The function "strcmp(const char *str1, const char *str2)" takes two parameters, the strings to compare and returns an integer result, <0 if str1 < str2, 0 if str1 = str2, or >0 str1 > str2.

Look at the documentation for the function strcmp(). Include the header file string.h and change your while loop to:

while(strcmp(Description, "zzz") != 0)

Collapse -

Basic C loop

by jeng In reply to Basic C loop

One more note... In C declaring a variable will contain uninitialized data (i.e. char Description[100]

In this case, you may want to initialize the variable Description to an empty string before using it. For example,

char Description[100];
Description[0] = '\0';

If you're only reading a line of string input from the console, you may want to look at the gets() or fgets() function.

Collapse -

Basic C loop

by mckay_w In reply to Basic C loop

The question was auto-closed by TechRepublic

Collapse -

Basic C loop

by rvk In reply to Basic C loop

The equality/relations operators can not be used that way.
It should be
while ( strncmp(Description,"zzz",3))
{

}
Thanks and Rgds
rk

Collapse -

Basic C loop

by mckay_w In reply to Basic C loop

The question was auto-closed by TechRepublic

Collapse -

Basic C loop

by mckay_w In reply to Basic C loop

This question was auto closed due to inactivity

Back to Web Development Forum
8 total posts (Page 1 of 1)  

Related Discussions

Related Forums