Δημοσιεύτηκε: 24 Ιουν 2011, 23:20
από migf1
Να σου δώσω κώδικα που διαβάζει μονοκόμματα μια γραμμή και μετά κρατάει έως τις 10 πρώτες λέξεις, αγνοώντας τις υπόλοιπες...
Κώδικας: Επιλογή όλων

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

#define MAXLINE 255+1
#define MAXTOKENS 10

// -----------------------------------------------------------------------------------
char *s_get(char *s, int maxlen)
{
register int i;

for (i=0; (s[i]=getchar()) != '\n' && i < maxlen-1; i++)
; // for-loop with empty body
s[i] = '\0'; // null-terminate s

return s;
}

// -----------------------------------------------------------------------------------
int s_tokenize(char *s, char *tokens[], int maxtokens, char *delimiters)
{
if ( !s || !*s )
return 0;

register int i=0;

tokens[0] = strtok(s, delimiters);
if (tokens[0] == NULL)
return 0;
for (i=1; i < maxtokens && (tokens[i]=strtok(NULL, delimiters)) != NULL; i++)
;

return i;
}

// -----------------------------------------------------------------------------------
int main( void )
{
char linebuf[ MAXLINE ];
char *stokens[ MAXTOKENS ];
int ntokens = 0;
register int i;

printf("Enter up to %d words: ", MAXTOKENS);
s_get( linebuf, MAXLINE);

ntokens = s_tokenize( linebuf, stokens, MAXTOKENS, " \t");

printf("\n%d typed words:\n", ntokens);
for (i=0; i < ntokens; i++)
printf("\t%s\n", stokens[i] );
putchar('\n');


printf("\npress ENTER to exit..."); fflush(stdin); getchar();
exit( EXIT_SUCCESS);
}