C help!

Started by
7 comments, last by ApochPiQ 13 years, 4 months ago
Hi,

I am trying to write some code in C, I am using fgets to read in the file, the file contains a combination of integers and letters. I need to extract only the numbers from the file. An example of the file is: Name LastName V050607008 3 4 5 6 7. the file is a series of lines as in the example. I only need the last 5 integers.

so far i have:
while(!feof(fp))
{
fgets(student,100,fp);

Any help is greatly appreciated!
Advertisement
This looks like your homework:) A suggestion would be to use strtok to tokenize the string by the space character, then get only the members you want and use atol (or a variation of it) to convert them to integers.
I agree with meeshoo actually, this doesn't look like your own project, but like a typical exercise you'd get as homework.

Personally I'd go with scanf over string tokenizing though.
Where exactly is your problem?
Quote:Original post by Thuder11
so far i have:
while(!feof(fp))
{
fgets(student,100,fp);


That's not a good way to organize your loop. All the functions you may use to read data have a return value that indicates whether they succeeded or not: Use it.

while (fgets(student, 100, fp) != NULL) {  ...}
I need to keep each 5 numbers associated with the correct name,will fgets take each line ( Names and Numbers) and store it in a element of my array or will it take the first letter and store in the first element,second letter in the second element and so on?
Also once I have the data in the array how would I "extract the data i need", I was thinking of using atoi but this function fails and first detection of a non integer.
Perhaps you want to use fscanf instead of fgets. Take a look at its documentation and write some little test program to see if you can get it to do what you want.
This is what I have:


int main(int argc, char *argv[])
{

char ch, student [100], num[100];
//int con [100];

int i,j= 0;

FILE * fp = fopen(argv[1],"r");

while(!feof(fp))
{
fgets(student,100,fp);

}
while(i<10)
{
ch = student;

if((ch >= '0') && (ch <= '9'))
{
num [j] = ch;
i++;
}
else {
i++;
}

j++;
}

printf("%s",num);

It works but will only print the first number that is in the file,almost as if it is not looping:(
Talk to your teacher and/or classmates if you need help. GameDev is not here to do your homework for you.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

This topic is closed to new replies.

Advertisement