user7227585
user7227585

Reputation:

Using Break to terminate for loop

So, A very basic program in which I want to allow the user to enter up to 10 words to a text file.

I want to make an exit clause such that If the user types a particular word, the program will stop

I am trying to use strcmp and comparing "exit" with the word entered by the user. If both match, then terminate. I know that if both are the same it returns 0, however I am unable to write:

{
char word[10];
FILE *fp;
int x;
int words = 0;

fp = fopen("c:\\CTEMP\\ExamProg1.txt", "w+");

{

    for (x = 0; x < 10; x++)

    {
        printf("\nType the word you want to add. Type exit to terminate: ");
        scanf("%s", word);

        if (strcmp(word, "exit") == 0)
        {
            break;
        }

        fprintf(fp, "%s\n", word);
        words++;
    }

    fclose(fp);
 }

scanf_s("%d");

}

How can I proceed to break the program when exit is inputted, instead of having to insert 'exit' twice?

Upvotes: 2

Views: 132

Answers (2)

Petr Skocik
Petr Skocik

Reputation: 60117

You'll likely want to read the word with:

scanf("%99s", word); // where 99 == your buffer size - 1
                     //word is probably a pointer in your example so no &

(scanf("%s",buf), like gets(buf), is potentially a huge security hazard) and then compare with "exit" like so:

 if (strcmp(word, "exit")==0) 

Here's a dummy example that works:

int main()
{
    char buf[10];
    while(EOF!=scanf("%9s", buf)){ 
        printf("s=%s\n", buf);
        if(strcmp("exit",buf)==0){
            puts("<exit>");
            exit(0);
        }
    }
    if(feof(stdin))
       puts("<EOF>");
    else
       puts("<ERROR>");

}

Upvotes: 2

Govind Parmar
Govind Parmar

Reputation: 21562

There are numerous things wrong with your code:

  1. scanf("%s", &word); since a string is a pointer or array in and of itself, the address-of operator should not be present in a call to scanf where the scanned input is being read into a string. Just use: scanf("%s", word);.

  2. strcmp(word, "exit")=0. The = operator is an assignment operator, not a comparison (what you want there is strcmp(word, "exit") == 0). Your test for the word "exit" is failing because you are not properly examining the return value from strcmp.

Upvotes: 4

Related Questions