Q
Q
qyui2021-01-02 22:55:18
C++ / C#
qyui, 2021-01-02 22:55:18

Why is data not being read on input from a file?

A simple example of a program taken from the book "Programming in C" by D. Griffiths. Takes two world coordinates (float) and an explanation for them (char []) from the input stream and formats this to the output stream in json format. When streaming from the keyboard, everything works fine. When reassigning: csv2json.exe < gps.txt > gps.json (as indicated in the book), the program writes that there are few parameters and their number = 0, i.e. actually refuses to read from a file. Such picture both in windows, and in Linux. Where did the dog dig?

#include <stdio.h>
#include<locale.h>

int main()
{
  
char *locale = setlocale(LC_ALL, "");

float latitude; 
float longitude; 
char info[80]; 
int started = 0;
int result;

printf("data=[");

while (1)	
{
  if ((result = scanf("%f,%f,%79[^\n]", &latitude, &longitude, info)) < 3)
  {
    printf("Слишком мало параметров %d", result);
    return 2;
  }
  else if(result >3)
  {
    printf("Слишком много параметров %d", result);
    return 2;
  }
  printf("The number of fields input is %d\n", result);
  if (started) 
    printf(",\n"); 
  else
  started = 1;
  if ((latitude < -90.0) || (latitude > 90.0)) {
    fprintf(stderr,"Неправильная широта: %f\n", latitude);
    return 2;
  }
  if ((longitude < -180.0) || (longitude > 180.0))	{
    fprintf(stderr, "Неправильная долгота: %f\n", longitude);
    return 2;
  }
  printf ("{latitude: %f, longitude: %f, info: '%s'}\n", latitude, longitude, info);
}

printf("]\n"); 



return 0;
}

File with coordinates:

42.363400,-71.098465,Speed=21  
42.363327,-71.097588,Speed=23
42.363255,-71.096710,Speed=17
42.363182,-71.095833,Speed=22
42.363110,-71.094955,Speed=14
42.363037,-71.094078,Speed=16
42.362965,-71.093201,Speed=18
42.362892,-71.092323,Speed=22
42.362820,-71.091446,Speed=17
42.362747,-71.090569,Speed=23
42.362675,-71.089691,Speed=14
42.362602,-71.088814,Speed=19
42.362530,-71.087936,Speed=16
42.362457,-71.087059,Speed=16
42.362385,-71.086182,Speed=21

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-01-02
@qyui

Most likely an error in the files. They are called differently than you pass in the parameters, or they are in a different directory, or they are empty. And you see the correct text in another file. Check all the titles again. Or the first line is empty.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question