Originally Posted by
vead
When I scan numbers I don't need to use enum or define but when I need to scan string or name why I need to use enum or something like define red
It is not about the "scanning", it is about the identifiers. Consider this program:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char name[10];
printf("Enter your name: ");
if (scanf("%9s", name) == 1)
{
if (strcmp(name, "vead") == 0)
{
printf("%s! Good to meet you.\n", name);
}
else
{
printf("%s is not vead.\n", name);
}
}
else
{
printf("Error: could not read input.\n");
}
return 0;
}
In this case, I used a string literal "vead" for comparison with the input stored in the variable named name. Now try to compile this program:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char name[10];
printf("Enter your name: ");
if (scanf("%9s", name) == 1)
{
if (strcmp(name, vead) == 0)
{
printf("%s! Good to meet you.\n", name);
}
else
{
printf("%s is not vead.\n", name);
}
}
else
{
printf("Error: could not read input.\n");
}
return 0;
}
The only thing that changed is that instead of using the string literal "vead", I now use the identifier vead. You should get an error similiar to what you encountered previously. Now compile and run:
Code:
#include <stdio.h>
#include <string.h>
#define vead "vead"
int main(void)
{
char name[10];
printf("Enter your name: ");
if (scanf("%9s", name) == 1)
{
if (strcmp(name, vead) == 0)
{
printf("%s! Good to meet you.\n", name);
}
else
{
printf("%s is not vead.\n", name);
}
}
else
{
printf("Error: could not read input.\n");
}
return 0;
}
This is the same as the previous program, except that I added a #define to define the identifier named vead to be the string literal "vead". This is a macro, so during preprocessing the compiler (or preprocessor) would replace the identifier vead with the string literal "vead", thereby resulting in a program essentially identical to the first one.
Note that I misspoke about the use of enum: in this case you are dealing with strings, so enum is not applicable, but #define could be used, or you could use say, a const string. Notice that I used stahta01's suggestion for strcmp instead of comparing with == since == would compare pointers rather than the string content.