Discussion Locked

Basic C loop

0 helpful
8 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

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);
....
}

8 replies

by germusic

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

by jeng

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)

by jeng

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.

by rvk

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

}
Thanks and Rgds
rk

This discussion is closed to new replies.