3

In this program I'm parsing a csv file with fgets, and based on my knowledge on c prog, it turns the file into an array.

So when I print it out with printf("%s",input) I get this 10,20,30 for example, but when i include printf("%s",input[0]) the program stops working. This is the program i am working on:

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

struct xa 
{
  int x;
  int y;
  int z;
} xo;

int main()
{
    FILE *dudufile;
    char filename[]="dodo.dat";
    char input[1679];
    dudufile=fopen(filename,"r");

    while ( fgets(input,1679, dudufile ) != NULL )
    {
        printf("%s\n",input);
        printf("%s\n",input[0]);
        struct xa;
        xo.y=input[1];
        printf("%d",xo.y);      
    }

    return 0;
}
aland
  • 4,829
  • 2
  • 24
  • 42

4 Answers4

5

Compile with warnings:

warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat]

Should be:

printf("%c\n",input[0]);
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • thanks for the info,i do have another question tho,lets say now tht ive parsed the file into an array with fgets and given tht its something like this 20,,50,how do i scan it and assign different variable to each of the interger and also including the white space. As far as i know if i use sscanf it wouldn't work with the white space – user3141640 Dec 28 '13 at 20:04
  • You can use `strtol` in a loop http://stackoverflow.com/questions/13952015/strtol-reusing-param – David Ranieri Dec 29 '13 at 00:59
4

This here is wrong:

printf("%s\n",input[0]);

Here you tell printf to print a string, but give a single character as argument. This leads to undefined behavior and the crash.

If the compiler doesn't already warn about it, you might want to enable more warnings. While warning messages are not errors from the compilers point of view, they often point out problems in your code, problems that often cause undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

input[0] is not a string (what %s expects), but a char. If you want to print that character, you need to use the %c format specifier.

Mat
  • 202,337
  • 40
  • 393
  • 406
2

Well, input[0] is not a pointer to a string as %s wants it to be.

If you want to print out one single character, you should use %c.

glglgl
  • 89,107
  • 13
  • 149
  • 217