user1883003
user1883003

Reputation: 57

Use scanf to get a string and then use an if statement with that string, instead of characters in c language

I know you can use scanf and get a character to use in an if clause, however, is there a way to do this with a string?

e.g.

printf("enter 'foo' to do 'bar', otherwise enter 'hay' to do 'wire');
scanf("%string", &stringNAME); //this is the part where I have no idea what to do

if (stringNAME == 'foo'){do bar} //here, issues occur with multicharacter character :/
if (stringNAME == 'hay'){do wire}

Upvotes: 0

Views: 3529

Answers (3)

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

You've almost got it, just a few tweaks.

char stringNAME[10];
printf("enter 'foo' to do 'bar', otherwise enter 'hay' to do 'wire');
scanf("%9s", stringNAME); 

if (!strcmp(stringNAME,"foo"){do bar}
if (!strcmp(stringNAME,"hay")){do wire}

Note the number in the scanf, the 9. That should be one less (Or smaller) than the size of your input string. Otherwise you risk a buffer overflow, which is nasty business. fgets is a better choice, because you are forced to limit the number of characters. This is how you would do that (Just replace the scanf line)

fgets(stringNAME, 10, stdin)

Upvotes: 1

RonaldBarzell
RonaldBarzell

Reputation: 3830

You can use scanf with the %s specifier to read strings, but be sure you are reading into a string (eg: char array, dynamically allocated char*, etc...). I can't see the rest of your code, but from the snippet you provide, I'm a bit suspicious of what &stringName is.

Here is an example of using scanf:

char s[100];
scanf("%s", s);

Now, having said that, please beware of using scanf to read strings. The example above for instance, will only return the first word if you type in a multi-word string.

If you know you need scanf fine; otherwise, when in doubt, use fgets.

Upvotes: 0

xcrazy360
xcrazy360

Reputation: 73

A string is a vector of char, comparing (str1 == str2) will return if they are in the same memory address.

if(strcmp(stringName, "foo") == 0){
//stringName is Foo
}

this will work

Upvotes: 0

Related Questions