itscharlieb
itscharlieb

Reputation: 313

C: Using scanf to accept a predefined input length char[]

I'm writing a C program that needs to accept user input of up to 100 characters, but the user is allowed to input less than that limit. I'm trying to implement this idea with a while loop that continues to accept char input until the user presses enter (ascii value of 13), at which point the loop should break. This is what I've written:

char userText[100]; //pointer to the first char of the 100
int count = 0; //used to make sure the user doens't input more than 100 characters


while(count<100 && userText[count]!=13){ //13 is the ascii value of the return key
    scanf("%c", &userText[count]);
    count++;
}

Launching from the command line, if I enter a few characters and then press enter, the prompt simply goes to a new line and continues to accept input. I think the problem lies with my lack of understanding how scanf receives input, but I'm unsure of how to change it. What can I do to make to loop break when the user presses enter?

Upvotes: 0

Views: 201

Answers (3)

Juri Robl
Juri Robl

Reputation: 5736

You should probably check against \n (=10) not 13. Also you check against the wrong count, it is already one to high.

int check;
do {
  check = scanf("%c", &userText[count]);
  count++;
} while(count<100 && userText[count-1]!='\n' && check == 1);
userText[count] = 0; // So it's a terminated string

On the other hand you could use scanf("%99s", userText); which allows up to 99 chars input (and one at the end for the 0).

The check for check == 1 looks for an error in reading, for example an EOF.

Upvotes: 0

BLUEPIXY
BLUEPIXY

Reputation: 40145

while(count<100 && scanf("%c", &userText[count]) == 1 && userText[count]!='\n'){
    count++;
}

Upvotes: 0

Cornstalks
Cornstalks

Reputation: 38217

Because you read into &userText[count] and then do count++, so you loop condition userText[count]!=13 is using the new value of count. You can fix it with:

scanf("%c", &userText[count]);
while(count<100 && userText[count]!='\n'){
    count++;
    scanf("%c", &userText[count]);
}

And as Juri Robl and BLUEPIXY are pointing out, '\n' is 10. 13 is '\r', which isn't what you want (most likely).

Upvotes: 1

Related Questions