![](/img/trans.png)
[英]How to read only integers from a file with strings, spaces, new lines and integers in C
[英]How to read string with spaces, integers and float values from a file in c?
嗨,首先,我要精確地說,我有一個以下格式的數據文件:
第一行包含一個字符串,后跟三個整數和一個float數據類型。
第二行包含帶空格的字符串,后跟三個整數和一個float數據類型。
最后一行包含一個字符串,后跟三個整數和一個float數據類型。
我的目的是讀取這些數據並分配給結構數組,數組中的結構包含一行包含字符串,3個整數和一個浮點數的行。 我使用以下代碼進行綁定,並成功讀取了其中字符串沒有空格但無法讀取帶有空格的字符串的行:
void readFromDatabase(struct student temp[], int *no) {
FILE *filepointer;
int i = 0;
if ((filepointer = fopen("database", "r")) == NULL) {
printf("Read error");
return;
}
while (fscanf(filepointer, "%10s\t%d%d%d%f\n", temp[i].name,
&temp[i].birthday.date, &temp[i].birthday.month,
&temp[i].birthday.year, &temp[i].gpa) != EOF && i < MAX_CLASS_SIZE) {
++i;
}
*no = i;
fclose(filepointer);
}
我得到了以下意外的輸出:
我試圖遍歷結構數組並以上述格式顯示數據。
但是我沒有得到3行輸出,而是得到了4行。
我真的需要一些有關此主題的幫助。
提前致謝...
我正在ubuntu 16.04下使用gcc來編譯和執行程序。
在fscanf
格式字符串中,使用%10[^\\t]
而不是%10s
。 這與名稱的每個字符匹配,直到制表符分隔符為止。
不幸的是,您沒有給出完整的示例,所以這是我要在Ubuntu 16.04上測試的小程序:
#include <stdio.h>
#include <stdlib.h>
#define MAX_CLASS_SIZE 4
struct student {
char name[11];
struct {
int date;
int month;
int year;
} birthday;
float gpa;
};
int main(void) {
FILE *filepointer;
int i = 0;
int no;
struct student temp[MAX_CLASS_SIZE];
if ((filepointer = fopen("data.txt", "r")) == NULL) {
printf("Read error");
return EXIT_FAILURE;
}
while (fscanf(filepointer, "%10[^\t]\t%d%d%d%f\n", temp[i].name,
&temp[i].birthday.date, &temp[i].birthday.month,
&temp[i].birthday.year, &temp[i].gpa) != EOF && i < MAX_CLASS_SIZE) {
++i;
}
no = i;
fclose(filepointer);
for(i = 0; i < no; i++) {
printf("%s: %d-%d-%d %f\n",
temp[i].name,
temp[i].birthday.date, temp[i].birthday.month, temp[i].birthday.year,
temp[i].gpa
);
}
return EXIT_SUCCESS;
}
根據您的格式字符串,我假設數據庫中的所有值都由制表符分隔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.