Pavoo
Pavoo

Reputation: 67

C while loop until user enters "quit"

Here's my code: 1. User types in two names, with a space in between. This means that two strings need to be read. I.e. input: John Doe.

  1. The strings are then checked in a char-array. (works fine).
  2. The while loop goes on until the user types "stop" - only "stop". How can I make it to stop directly if "stop" is entered - without the need to check the second string?

The code:

while(bool==false)
{
    scanf("%20s%20s", name1, name2);

    if(strcmp(name1, "stop")==0)
    {
        break;        
    }
    // but still the second name has to be entered

    rest of code...

}

Thanks for any tips!

Upvotes: 0

Views: 2065

Answers (2)

Arjun Sreedharan
Arjun Sreedharan

Reputation: 11453

You can put to use the regular expression character class support provided by scanf.

You could do:

scanf("%s%[^\n]s", name, temp);

Here, your first word is mandatory while second is optional.

When you input 2 words, your temp would have a leading space. If you want to directly avoid it, you can do so by:

char *p = temp;
scanf("%s%[^\n]s", name, p++);

Here, you can later access your 2 words using name and p

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409136

I suggest you use fgets to get the input, check for the "stop" string, and then use sscanf to parse the input.

Upvotes: 1

Related Questions