This program is really getting on my nerves:
I am trying to read a line from a file with following information:
512 MB 136.186.99.1 00-25-B3-0B-31-29
which is in the format of double string string string
and the code I'm using is
fscanf(filePtr, "%lf %s %s %s", &Computer[i].ram, Computer[i].ram_unit, Computer[i].MACNo, C开发者_如何学JAVAomputer[i].IPV4);
but when I print Computer[i].ram_unit
I get:
MB136.186.99.1
Please help me to find out what I'm doing wrong. Let me know if you like me to paste the entire code.
Thanks
First, you have MACNo
and IPV4
reversed in your fscanf
relative to the sample input.
Can't tell for sure without seeing the structure definition, but it looks like a possible array overrun. For example, if your Computer
was defined like this:
struct ComputerType {
double ram;
char ram_unit[2]; /* This needs to be 3 (assuming unit is always 2 chars long) */
char IPV4[16];
char MACNo[17];
};
when you read "MB" into ram_unit
, you could end up having
ram_unit[0] = 'M'
ram_unit[1] = 'B'
IPV4[0] = '\0'
And then when you read in the IP address into IPV4 that makes it
ram_unit[0] = 'M'
ram_unit[1] = 'B'
IPV4[0] = '1'
IPV4[1] = '3'
[etc]
IPV4[10] = '1'
IPV4[11] = '\0'
When you go to print out ram_unit
, the print function will start at the memory location &ram_unit[0]
and keep on printing until it sees a NULL
. But since the NULL
ended up in IPV4[0]
and that got overwritten when you read in the IP address, it won't stop printing until it gets to the NULL at IPV4[11]
and so you get the unexpected concatenation.
To read a line from a file like this one:
1603 Lu,Ma,Mi,Ju,Vi,Sa,No Mar del Plata 08:25 09:20 Aerolineas Argentinas
Use this:
fscanf(pf, "%d %2s,%2s,%2s,%2s,%2s,%2s,%2s %[^\n]s %d:%d %d:%d %[^\n]s",
®istro.code,
®istro.dia.lunes,
®istro.dia.martes,
®istro.dia.miercoles,
®istro.dia.jueves,
®istro.dia.viernes,
®istro.dia.sabado,
®istro.dia.domingo,
®istro.destino,
®istro.hSalida.hh,
®istro.hSalida.mm,
®istro.hLlegada.hh,
®istro.hLlegada.mm,
®istro.aerolinea
);
精彩评论