Beginner Question: Problem with scanf and strings. Help!
First off how does scanf know that this: %[^\n] is supposed to be formatted for a String? Shouldn't %s need to be in there? According to the syntax it's not supposed to be.
Anyway, my real question is when I run this program (below) it lets me type in my first name, but then when I press Return it skips over letting me enter my last name and shows this:
Code:
What is your FIRST name: Bryan
What is your LAST name: Your FULL name is Bryan and it is 6 long.
Code:
#include <stdio.h>
#include <string.h>
int main (int argc, const char * argv[]) {
char firstname[31];
char lastname[31];
char fullname[63];
printf( "What is your FIRST name: " );
scanf( "%[^\n]", firstname ); // accepts everything until it sees a \n
printf( "What is your LAST name: " );
scanf( "%[^\n]", lastname ); // accepts everything until it sees a \n
strcpy( fullname, firstname );
strcat( fullname, " " );
strcat( fullname, lastname );
printf( "Your FULL name is %s and it is %d long.", fullname, strlen(fullname) );
return 0;
}
ok, i tried adding this (still doesn't work)
I figured using a fflush(stdin); would clear the buffer but it doesn't seem to make a difference... I'm clueless how to get this working as expected
Code:
#include <stdio.h>
#include <string.h>
int main (int argc, const char * argv[]) {
char firstname[31];
char lastname[31];
char fullname[63];
printf( "\nWhat is your FIRST name: " );
scanf( "%[^\n]", firstname );
fflush(stdin); // this doesn't seem to work
printf( "\nWhat is your LAST name: " );
scanf( "%[^\n]", lastname );
strcpy( fullname, firstname );
strcat( fullname, " " );
strcat( fullname, lastname );
printf( "\nYour FULL name is %s and is %d characters long.", fullname, strlen(fullname) );
return 0;
}