Elis Jones
Elis Jones

Reputation: 337

Using scanf with a while loop to input two separate strings

I'm trying to make a program which reads in a name and number which is separated with a space and allocates the input to a structure.

typedef struct {

    char name [20];
    char number [12];
} Entry;

The scanf function is in a while loop, and I'd like it to break from the while loop if the input is "."

while(strcmp(e.name,".")!=0) {
    scanf("%s %s", e.name, e.number );
}

But using the above code means that the user has to input two periods. I was wondering if anybody had any advice on how I could make it break from the loop after the first ".".

Upvotes: 1

Views: 1289

Answers (2)

Spikatrix
Spikatrix

Reputation: 20244

Use two conditions:

while(1) {  //infinite loop

    scanf("%19s", e.name);
    getchar(); //remove the \n from the stdin
    if(strcmp(e.name,".")==0)
        break;

    scanf("%11s", e.number);
    getchar(); //remove the \n from the stdin
    if(strcmp(e.number,".")==0)
        break;
}

The 19 and 11 tells scanf to scan a maximum of that much characters and then,append a \0 at the end.

Upvotes: 2

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

I would recommend, replace your scanf() with fgets(). Check the man page for the syantax.

  1. Read the input [yes, a sinle line input, separated with a space]
  2. tokenize and validate the input
  3. do the processing.

This way, comparing the input with a . (in case of exit condition) will do the job.

Don't forget to take care of the trailing \n which will be read and stored into buffer by fgets()

Upvotes: 2

Related Questions