Originally Posted by
BEN10
It worked properly except for it's not printing the age properly. I think what you're trying to do is hitting enter after the "Enter name: (20 maximum characters)" line.
Yes.. I modified the code and applied sebastiani's code:
Code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *getString( char *buffer, size_t size, FILE* input );
int main()
{
const int size = 22;
char name[ size ];
char age[ size ];
fputs( "Enter name: ", stdout );
getString( name, size, stdin );
fputs( "Enter age: ", stdout );
getString( age, size, stdin );
fprintf( stdout, "Name is: %s\n",name );
fprintf( stdout, "Age is: %s\n", age );
return 0;
}
char *getString( char *buffer, size_t size, FILE *input )
{
char *newLine, *stringResult = fgets( buffer, size, input );
if( stringResult )
{
newLine = strchr( stringResult, '\n' );
if( newLine )
*newLine = '\0';
}
return stringResult;
}
The size of the string is 22, if I entered more than 22 the age input will accept the excess buffer that was from the first input. So I can't input for the age at all and the age will print out the excess from the first input.
here's the output of the program:
Code:
Enter name: Maria Theresa Acosta D
Enter age: Name is: Maria Theresa Acosta
Age is: D
Process returned 0 (0x0) execution time : 42.703 s
Press any key to continue.
As you can see the 22nd character is D and it's directly retrieved by age...