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 "."
.
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments