0
char getText() {
    char text[100];
    int c = 0;
    do {
        __fpurge(stdin);
        printf("Enter text: ");
        gets(text);
        while (text[c] != '\0') {
            if ((text[c] != '@')) {
                if (text[c] == '@') {
                    printf("Contain @\n");
                }
            } else break;
            c++;
        }
    } while (1);
    return text;
}

I have this function check input string user enter. If string contain '@'. Require user enter again
If string not contain '@'. Accept string and return string.
But I can't break the loop. Anyone can help me solve problem. Thank first.

Đức Long
  • 117
  • 1
  • 9
  • 2
    read your code out loud: "if text[c] != @ then is text[c] = @" - hang on, it can't possibly be != and = at the same time... – John3136 Jul 09 '20 at 03:47
  • Just a side note: You need to reset `c` to 0 before entering the inner `while`-loop. – the busybee Jul 09 '20 at 06:12
  • The title says: "special characters such as ...". I would take this as **any** special character with `@` only being an example. – Gerhardh Jul 09 '20 at 06:38
  • That break is only breaking out of the inner loop. It's not breaking out of the while(1) loop. You probably want to put a conditional in the while(1) loop that checks if you've got a good string. – yhyrcanus Jul 09 '20 at 15:43

1 Answers1

0

Rather writing:

while (text[c] != '\0') {
    if ((text[c] != '@')) {
        if (text[c] == '@') {
            printf("Contain @\n");
        }
    } else break;
}

The followed condition tells the compiler to compare the text[c] and @ when the text[c] isn't equal to @, which makes no sense at all.

Try this:

while (text[c] != '\0') {
    if (text[c] == '@') printf("Contain @\n");
    else break;
    // ...
}

Also, remember that using gets() is considered to be dangerous, learn how & why.

You may rather use the fgets():

fgets(text, MAX, stdin); // #define MAX 100, playing with magical numbers
                         // isn't considered good
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34