[英]How to read only digits from a text file with fscanf in C
For part of my program i have to get info from a text file called "options.txt". 对于我程序的一部分,我必须从一个名为“ options.txt”的文本文件中获取信息。 This file is like that: 该文件是这样的:
Team number 10 win point 2 draw point 1 lose point -1
I Wrote this code but it fill the options array with only zeros: 我写了这段代码,但是它只用零填充了options数组:
int options[4];
getOptions(){
FILE *filePtr;
if((filePtr=fopen("options.txt","r"))==NULL){
puts("file could not be opened");
} else {
for(i=0;i<4;i++) {
fscanf(filePtr, "%d", &options[i] );
}
const int teamNumber=ayarlar[0]; //first element of the array is teamNumber
struct teams team[teamNumber]; // teamNumber necessary for teams
}
You can use scanf("%*[^-0-9]");
您可以使用scanf("%*[^-0-9]");
to scan and discard all characters that are not digits or -
. 扫描并丢弃所有不是数字或-
字符。 So then you loop looks like: 因此,您的循环如下所示:
for(i=0;i<4;i++) {
fscanf(filePtr, "%*[-0-9]");
if (fscanf(filePtr, "%d", &options[i] ) != 1)
fprintf(stderr, "error reading file");
}
Note that you should ALWAYS check the return value of scanf before using any of the resulting values, to ensure that they were successfully read and converted. 请注意,在使用任何结果值之前,应始终检查scanf的返回值,以确保已成功读取和转换它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.