简体   繁体   中英

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. Ie 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!

我建议您使用fgets获取输入,检查"stop"字符串,然后使用sscanf解析输入。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM