4

I am really new to C programming and this is a part of an assignment. I am trying to read a comma separated text file in the format:

 [value1], [value2]

in C and trying to pass them as string and int parameter into a function. I have tried using the sscanf() and even manipulation with fgetc() without much help. The space after the comma is proving to be a problem.

Example:

 2001, 102
 1314, 78
 0410, 910
 ...

Please help me out.

Thank you.

13
  • 5
    Post what you have tried. Commented Oct 18, 2014 at 19:07
  • Possible duplicate - please see this: stackoverflow.com/q/12911299/1726419 Commented Oct 18, 2014 at 19:09
  • In fact, you can't possiby. The csv-format may contain quoted commas in the data fields and isn't a simple thing to program as a beginner. If you wouldn't solve the simplest case only, you could use a good library and the examples therein: sourceforge.net/projects/libcsv Commented Oct 18, 2014 at 19:12
  • 2
    @SouradeepSinha why don't you give it another try before asking here? If it's an assignement, you are supposed to learn from it ... Commented Oct 18, 2014 at 19:16
  • 2
    This question appears to be off-topic because it is just asks for code, shows not attempt to solve it. Commented Oct 18, 2014 at 19:23

1 Answer 1

3

Thanks to @rubberboots for the help.

#include <stdio.h>
#include <string.h>

void main()
{
    FILE *fp = fopen("user.dat", "r");
    const char s[2] = ", ";
    char *token;
    int i;
    if(fp != NULL)
    {
        char line[20];
        while(fgets(line, sizeof line, fp) != NULL)
        {
            token = strtok(line, s);
            for(i=0;i<2;i++)
            {
                if(i==0)
                {   
                    printf("%s\t",token);
                    token = strtok(NULL,s);
                } else {
                    printf("%d\n",atoi(token));
                }       
            }
        }
        fclose(fp);
    } else {
        perror("user.dat");
    }   
}   

user.dat file:

1000, 76

0095, 81

2910, 178

0001, 1

Output:

1000 76

0095 81

2910 178

0001 1

Sign up to request clarification or add additional context in comments.

2 Comments

Curious, why print the string version of what was read for the first number and use a number version for the second number? Would not is be more consistent to either print both as strings or both as numbers?
Assignment woes. It doesn't make much sense to me as well. I guess the professor wanted us to learn and kill two birds with one printf statement. :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.