C fscanf奇怪地连接两个字符串

时间:2011-05-25 01:14:47

标签: scanf

这个程序让我很紧张:

我正在尝试从包含以下信息的文件中读取一行:

512 MB 136.186.99.1 00-25-B3-0B-31-29

格式为double string string string

我正在使用的代码是

fscanf(filePtr, "%lf %s %s %s", &Computer[i].ram, Computer[i].ram_unit, Computer[i].MACNo, Computer[i].IPV4);

但是当我打印Computer[i].ram_unit时,我得到了:

MB136.186.99.1

请帮我弄清楚我做错了什么。如果您希望我粘贴整个代码,请告诉我。

由于

2 个答案:

答案 0 :(得分:3)

首先,相对于示例输入,MACNo IPV4fscanf相反。

如果没有看到结构定义,就无法确定,但它看起来像是一个可能的数组溢出。例如,如果您的Computer定义如下:

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];
};

当您将“MB”读入ram_unit时,您最终可能会

ram_unit[0] = 'M'
ram_unit[1] = 'B'
IPV4[0] = '\0'

然后当您将IP地址读入IPV4时,将其作为

ram_unit[0] = 'M'
ram_unit[1] = 'B'
IPV4[0] = '1'
IPV4[1] = '3'
[etc]
IPV4[10] = '1'
IPV4[11] = '\0'

当您打印ram_unit时,打印功能将从内存位置&ram_unit[0]开始并继续打印,直至看到NULL。但是,由于NULL最终在IPV4[0]并且在您读取IP地址时被覆盖,因此它将不会停止打印,直到它在IPV4[11]处变为NULL,因此您将获得意外的连接。

答案 1 :(得分:0)

要从像这样的文件中读取一行:

  

1603 Lu,Ma,Mi,Ju,Vi,Sa,No Mar del Plata 08:25 09:20 Aerolineas Argentinas

使用此:

fscanf(pf, "%d %2s,%2s,%2s,%2s,%2s,%2s,%2s %[^\n]s %d:%d %d:%d %[^\n]s",
    &registro.code,
    &registro.dia.lunes,
    &registro.dia.martes,
    &registro.dia.miercoles,
    &registro.dia.jueves,
    &registro.dia.viernes,
    &registro.dia.sabado,
    &registro.dia.domingo,
    &registro.destino,
    &registro.hSalida.hh,
    &registro.hSalida.mm,
    &registro.hLlegada.hh,
    &registro.hLlegada.mm,
    &registro.aerolinea
);