Δημοσιεύτηκε: 17 Φεβ 2012, 20:36
Κάποια σημεία τα έχεις καταλάβει λάθος, κάνε σύγκριση με τα δικά μου σχόλια (πόσταρε στο μεταξύ και την απορία σου)...
- Κώδικας: Επιλογή όλων
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXINPUT 256+1 /* max # of chars to read from stdin */
int main( void )
{
char input[ MAXINPUT ] = {'\0'}; /* c-string, for reading 1 stdin line*/
char *s = NULL; /* c-string (read from stdin) */
int maxlen = 0; /* max len of s (read from stdin) */
int len = 0; /* current len of s (will calculate) */
do {
printf("Give the len: ");
fgets( input, MAXINPUT, stdin );/* read the whole stdin line as input */
maxlen = atoi(input); /* convert to int & assign to maxlen */
} while ( maxlen < 1 ); /* demand positive, non-zero maxlen */
maxlen++; /* for the '\0' at the end */
s = calloc(maxlen, sizeof(char)); /* alloc memory & make s point to it */
if ( !s ) { /* mem allocation failed */
fputs("*** error, out of memory!\n", stderr);
exit( EXIT_FAILURE ); /* exit program with failure signal */
}
printf("Give a string : ");
fgets(s, maxlen, stdin); /* read s directly from stdin */
len = strlen(s); /* calc current len of given s */
if ( s[ len-1 ] == '\n' ) /* check if s has a '\n' before '\0'*/
s[ len-1 ] = '\0'; /* ... and remove it if it has */
printf("You gave the string: %s\n", s);
system("pause");
free( s ); /* release mem reserved for s */
exit( EXIT_SUCCESS);
}