I can do the problem in java, but I was wondering if I could write the code this way in C. Can I store a series of pointers to strings in an array? So that array[0] could contain a pointer to an string in memory? I get a segmentation fault when i run my code, and a bunch of formatting errors. The point is to create a simple mail merge type program, where each line of the file being read looks like |string|string|string| etc.. up to 9 fields.
Code:#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXSIZE 25 int main( int argc, char *argv[] ) { char line[ MAXSIZE ]; //hold lines of file char fields[ MAXSIZE ]; //hold tokenized strings (need to be a pointer?) char *token = NULL; FILE *read = NULL; //file to be read int i; read = fopen( "data.txt", "r" ); while( !feof( read ) )//read each record { fgets( line, MAXSIZE, read ); token = strtok( line, "|" ); //tokenize the line i = 0; while( token ) { fields[ i ] = token; //store pointers in array (if possible?) token = strtok( NULL, "|" ); i++; } //formatting... printf( "Welcome back, %s %c\n", fields[ 1 ], '!' ); printf( "We hope that you and all the members\n"); printf( "of the %s %s", fields[ 0 ], " family are constantly\n" ); printf( "reminding your neighbors there\n"); printf( "on %s %s", fields[ 5 ], " to shop with us\n" ); printf( "As usual, we will ship your order to\n"); printf( "%4s %2s %2s %2s\n", fields[ 3 ], fields[ 1 ], fields[ 2 ], fields[ 0 ] ); printf( "%4s %2s\n", fields[ 4 ], fields[ 5 ] ); printf( "%4s %s %s %s\n", fields[ 6 ], ", ", fields[ 7 ], fields[ 8 ] ); } return EXIT_SUCCESS; }Code:Errors: merge.c: In function âmainâ: merge.c:25: warning: assignment makes integer from pointer without a cast merge.c:30: warning: format â%sâ expects type âchar *â, but argument 2 has type âintâ merge.c:32: warning: format â%sâ expects type âchar *â, but argument 2 has type âintâ merge.c:34: warning: format â%sâ expects type âchar *â, but argument 2 has type âintâ merge.c:36: warning: format â%4sâ expects type âchar *â, but argument 2 has type âintâ merge.c:36: warning: format â%2sâ expects type âchar *â, but argument 3 has type âintâ merge.c:36: warning: format â%2sâ expects type âchar *â, but argument 4 has type âintâ merge.c:36: warning: format â%2sâ expects type âchar *â, but argument 5 has type âintâ merge.c:37: warning: format â%4sâ expects type âchar *â, but argument 2 has type âintâ merge.c:37: warning: format â%2sâ expects type âchar *â, but argument 3 has type âintâ merge.c:38: warning: format â%4sâ expects type âchar *â, but argument 2 has type âintâ merge.c:38: warning: format â%sâ expects type âchar *â, but argument 4 has type âintâ merge.c:38: warning: format â%sâ expects type âchar *â, but argument 5 has type âintâ



LinkBack URL
About LinkBacks




I used to be an adventurer like you... then I took an arrow to the knee.