Reading combinations of string and integer from file in C

风格不统一 提交于 2019-12-11 10:33:25

问题


I am novice to C langugage, so please bear with me. I've tried to read a file which contains strings but output obtained is single character.

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

#define CALLOC(num, type) ((char*)calloc (num, sizeof(char)))
#define FREE(addr) (free((void*) (addr)))

int i, count;
char *x, *y, *z;

int main (void) 

{

FILE *stream;
if ( (stream = fopen ( "test.txt", "r" )) == NULL )
{ printf ("Cannot read the new file\n");
exit (1);
}

count = 3;

x=CALLOC(count, char);
y=CALLOC(count, char);
z=CALLOC(count, char);


for ( i=0; i<count; i++ ) 
{ fscanf (stream,"%c %c %c", &x[i], &y[i], &z[i]);
printf ("\n %d %c %c %c ", i, x[i], y[i], z[i]);
}

FREE(x);
FREE(y);
FREE(z);

fclose (stream);

}

Input test.txt file contains

1 ab 1
2 aa 5
1 cc 1

current output

 0 1 a b
 1   1 2
 2   a a 

Expected output

 0 1 ab 1
 1 2 aa 5
 2 1 cc 1

I doubt whether I should use a character array but it seems not working and I feel reading a int using char is acceptable. Here I require the expected output, for this any method/suggestion is appreciated.


回答1:


%c reads in only one char. So it's not going to read ab as a single char. Your lines in file and your formats don't correctly to read an entire line.

A simple approach is to use fgets() and print the entire line:

char line[256];
i = 0;

while(fgets(line, sizeof line, stream))
{
   printf ("%d %s", i, line);
   i++;
}

By the way, macros for calloc and free are unnecessary. They really don't make the code any easier to read than directly using those functions.

And the casts in them are also unnecessary.




回答2:


The problem is you have the scan file. %c read a 8bit value. You scanned 3 char, but the file is contain 4 characters. If you don't use to be the value of the x, y, z I don't understand why use malloc.

Here a working source:

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

int main() {
  int count,i;
  char w,x,y,z;
  FILE *stream;
  if((stream = fopen("test.txt","r")) == NULL) {
    printf("Cannot read the new file\n");
    return 1;
  }
  count = 3;
  for(i=0;i<count;++i) {
    fscanf(stream,"%c %c%c %c\n",&w,&x,&y,&z);
    printf("%d %c %c%c %c\n",i,w,x,y,z);
  }
  return 0;
}



回答3:


for ( i=0;i<count; i++ ) 
        { 
            fscanf (stream,"%s %s %s", x, y, z);
            printf ("\n %d %s %s %s ", i, x, y, z);  
        }

You can modify your loop to this.This loop will read file until end of file and you have to use %s as ab is a string not charater so it can't be stored in a char variable.



来源:https://stackoverflow.com/questions/31536689/reading-combinations-of-string-and-integer-from-file-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!