简体   繁体   English

从txt文件读取C中的字符串

[英]Read strings in C from txt file

I'm trying to read some strings from a txt file. 我正在尝试从txt文件读取一些字符串。 Each line has a 5 digit number, a full name that occupies 51 characters (including spaces), 2 city names, each one occupyng 11 characters including spaces, and one number. 每行有一个5位数字,一个全名,占51个字符(包括空格),两个城市名称,每个占11个字符(包括空格)和一个数字。 Example: 例:

12345António Manuel Silva Mendes                        Frankfurt  Varsovia    1

I can now scan the first 2 strings, but I can't scan the city names, nor the last number. 现在,我可以扫描前两个字符串,但是无法扫描城市名称或最后一个数字。

Here's the struct: 这是结构:

typedef struct bilhete{

    int BI;
    char nome[51];
    char partida[11];
    char chegada[11];
    int data[2];

}BILHETE;

here's the way I'm reading the file 这是我读取文件的方式

while(!feof(fp)){

        fscanf(fp,"%d%51[^\n]s%11c%11c%d\n", &bilhete.BI, bilhete.nome, bilhete.partida, bilhete.chegada, &bilhete.data);

What am I doing wrong? 我究竟做错了什么? when I print the city names, nothing appears! 当我打印城市名称时,什么都没有出现!

Since you have fixed columns, I would consider just reading in the data and doing my own scanning with something like: 由于您具有固定的列,因此我将考虑读取数据并使用类似以下内容进行自己的扫描:

char linein[200];
char *p;

while (fgets(linein, sizeof(linein), fp))
{
    char biBuf[10]={0};
    char dataBuf[10]={0};

    p=linein;
    memcpy(biBuf,linein,5);
    bilhete.BI=atoi(biBuf);
    p+=5;
    memcpy(bilhete.nome,p,51);
    p+=51;
    memcpy(bilhete.partida,p,11);
    p+=11;
    memcpy(bilhete.chegada,p, 11);
    p+=11;
    memcpy(dataBuf,p,2);
    bilhete.data[0]=atoi(dataBuf);
    printf("%.51s %d\n",bilhete.nome, bilhete.data[0]);
}

I am not sure what you wanted to do with the data variable but this will give you an integer. 我不确定您要使用data变量做什么,但这将为您提供一个整数。 Observe, the biBuf and dataBuf variables are allocated in the loop so they get set to zeros each time. 请注意,biBuf和dataBuf变量在循环中分配,因此每次将它们设置为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM