#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int car, stri, i, t, j;
char *fullcara = NULL, *default0;
while (1) {
printf("N strings de X chars: ");
if( scanf("%d %d", &stri, &car)==2 && stri>0 && stri<=100 && car>1 && car <= 80) break;
}
fullcara= (char *) malloc( car*stri*sizeof(char) );
if ( fullcara == NULL ) {
printf("Not enough contiguous RAM.");
exit;
}
fgets(&fullcara[0], car, stdin); /* clean the buffer the 1st time */
for ( i=0; i<stri; i++ ) {
printf("Sentence: ");
fgets( &fullcara[i*car], car, stdin);
}
printf("\n");
for ( i=0; i<stri; i++) {
for ( t=1; t<stri; t++) {
for ( j=0; fullcara[i*car+j] != '\n'; j++) {
if ( fullcara[i*car+j] != fullcara[t*car+j] ) fullcara[t*car] = '\0';
}
}
}
for ( i=0; i<stri; i++) {
for ( t=0; fullcara[i*car+t] != '\0'; t++) {
printf("%c", fullcara[i*car+t]);
}
}
printf("\n");
return 0;
}
2 replies to this topic
#1
Posted 22 January 2012 - 07:03 AM
I want to create a program that creates N strings of X chars, that detects similar strings and skips the repeated when printing. The program compiles perfectly, however in some cases it gives out some errors like memory violations (segmentation fault) and only reads the 1st string (buffer issue probably, fflush not an option since it just works for windows (I reckon)). There is also a problem with fgets, if I write 20 chars and the size was 4, it should read the 2 chars and the rest should be the the '\n'(0A) and the '\0' (00).
|
|
|
#2
Posted 24 January 2012 - 05:58 AM
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int car, stri, i, t, j;
char **fullcara = NULL;//, *default0;
while (1) {
printf("N strings de X chars: ");
if( scanf("%d %d", &stri, &car)==2 && stri>0 && stri<=100 && car>1 && car <= 80) break;
}
fullcara= (char **)malloc(car*sizeof(char*));
if ( fullcara == NULL ) {
printf("Not enough contiguous RAM.");
return 1;
}
for(i=0; i < car; ++i)
{
fullcara[i] = (char *)malloc((stri+1)*sizeof(char)); // +1 for /0
}
for ( i=0; i<stri; i++ ) {
fflush (stdin); /* clean the buffer the 1st time */
printf("Sentence: ");
scanf("%s",fullcara[i]);
fullcara[i][car]='\0';
}
printf("\n");
for ( i=0; i<stri; i++) {
printf("%s", fullcara[i]);
free(fullcara[i]);
}
free(fullcara);
printf("\n");
return 0;
}
#3
Posted 10 May 2012 - 09:43 AM
You need to change 3 things...
- Use double pointer (**) to hold N string
- Use scanf("%s", fullchar[i]) instead of fgets
- Use space(' ') character to replace the duplicate characters. You are using '\0' character -- this causes to print characters till the first '\0' character in a string.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account

Back to top










