C strings

Associate
Joined
18 Mar 2007
Posts
291
Hi guys, just after a bit of advice as to how to go about this problem, not after a solution.

What I have to do is read in a text file and put the characters in it into strings. however, when there is a comma, i need to put it in a new string and i need to ignore whitespace and punctuation.

Probably a bad example, so here's an example:

The dog,sat, on, the.

Would be:

string1: "The"
string2: "dog"
string3: "sat"
string4: "on"
string5: "the"

However, what I don't know is how many characters each string will be.

To do the string allocation, would I have to assign it once I know how many characters there are, i.e: char string1[NO_OF_CHARACTERS]?

I'm assuming my best option would be to use fgetc and putting it in a while function, saying while(!ispunct(fgetc(file)) to ignore the punctuation and doing another one saying while(!isspace) etc...?

Just trying to brainstorm a bit here. Any advice would be very helpful.

Cheers.
 
hey guys, what i've got so far is this:

Code:
#include <string.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    
    FILE *fp;
	char delimiters[] = " ,";
	char string[10], *string1, *string2, *string3, *string4;
	int i=0,j;

    if ((fp=fopen("test.txt", "r"))==NULL) {
	    printf("Error opening file");
        exit(1);
    }
    
	while(1) {
		string[i]=fgetc(fp);
		
		if(feof(fp)){
			break;
		}
		i++;
	}
	
	for(j=0; j<i; j++) {
            printf("%c", string[j]);
    }
    
    printf("\n");


	string1 = strtok (string, delimiters);
	printf("%s\n", string1);
	string2 = strtok (NULL, delimiters);
	printf("%s\n", string2);
	string3 = strtok (NULL, delimiters);
	printf("%s\n", string3);
	string4 = strtok (NULL, delimiters);
	printf("%s\n", string4);

	return 0;
}

however, i know there is going to be a maximum of 4 strings per line, but there could be less than 4 strings.

the results returned by the file containing:
Code:
"The,        cat, is"

are:

Code:
The
cat
is
,


i.e: it has a ',' at the end :confused: any ideas?

i realise that this would only be a solution for one line and will need to work with more lines in the future, any tips?
 
i do need to store the strings, but just from one line at a time. what i'm planning on doing is storing the strings line-by-line and performing checks on each string. for example, if string1 contains a number, post an error message and quit etc. however, this is for later on.

thanks.
 
ahh thats great thanks lads.

also, does anyone have a good tutorial on pointers in C? i start getting a bit lost at pointers to pointers i.e: ** and just pointers for storing strings etc.

thanks
 
ahh ok brilliant mate, i'm gunna have a good read over that and a tutorial over at gamedev tomorrow and see what i can come up with.

thanks for your help.

expect me back tomorrow!
 
Back
Top Bottom