Click to See Complete Forum and Search --> : Scanf only takes up to the first space?


Charred_Phoenix
05-31-2003, 08:28 PM
I should say before we begin that i'm getting back into C now after a long break, so you'll probably get a lot of stupid questions from me in the next few days ^_^


#include <stdio.h>
#include <string.h>

int main(void) {
char messagein[255];
char messagemid[2];
char messageout[510];
char ccc;
int ccn;

printf("\nEmoticon encryptor v0.3a\n\nEnter message (255 characters or less):");
scanf("%s", messagein);
strcat(messagein, "\xFF");

ccn = 0;
ccc = messagein[ccn];

while(ccc != '\xFF') {
if(ccc != ' ') {
printf("\n\nDebug info: %d-%c-%s-%s\n\n", ccn, ccc, messagein, messageout);
strcat(messageout, "(");
sprintf(messagemid, "%c", ccc);;
strcat(messageout, messagemid);
strcat(messageout, ")");
ccn++;
ccc = messagein[ccn];
}
else if(ccc == ' ') {
strcat(messageout, " ");
}
}

printf("\n%s\n", messageout);


return 0;
}


If you enter a multi word message (that is, a message with spaces in it) you only get the first word done, anyone know the problem?

-_-'

salil
06-01-2003, 09:42 AM
Try looking up the man page for scanf using

%man scanf

It says there that scanf will match a sequence of non-white space characters only. Thats why it is only looking until the first whitespace.

Besides using %s with scanf can be a security risk
in critical applications.

bwkaz
06-01-2003, 05:17 PM
To input a line with spaces in it, use getline (for C++) or fgets(stdin) for C. Make sure you read the fgets manpage, too, though, because it has some strange features.

Charred_Phoenix
06-02-2003, 03:21 AM
Thanks, and salil, I don't plan for this application to be suid so buffer overflows aren't really a problem :)