Sign in to follow this  
Thuder11

C help!

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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) {
...
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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[i];

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:(

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.
Sign in to follow this