每当我使用fscanf
读取文件内容时,在这种情况下是国家名称后面跟一个空格,国家资本后跟一个空格,然后是人口,它会被成功读取,直到名称为国家不同,如阿拉伯联合酋长国"。我使用了我能找到的所有建议,但在新的线路运营商之前似乎仍无法解析。相反,它会在联合之后停止扫描,并让fscand
的酋长国读入我的国家资本价值,然后将所有东西都抛弃。任何建议都会有所帮助,因为我是一个相当新的程序员。
terminal
egypt cairo 81015887.000000
madagascar antanonariva 21926221.000000
zimbabwe harare 12521000.000000
united arab 0.000000
mirates abu 0.000000
habi 8264070 0.000000
nited states 0.000000
ashington, d. 0.000000
. 312642000 0.000000
osnia herzegovina 0.000000
的main.cpp
#include <stdio.h> //for testing within main
#include <string.h> //for testing within main
#include <stdlib.h>
#include "headers.h"
int main()
{
int size, i, g; //size of countries that will be read in
char usrC; //user choice
FILE * fileP;
char UI[25];
Country * c[10];
ask(UI);
size = oSesame(UI, fileP, c);
if(size==0) //if file returns as empty
{
return 0;
}
for(g=0;g<size;g++)
{
printf("%s %26s %-11lf\n ", c[g]->cntName, c[g]->capName, c[g]->population);
}
return 0;
}
header.h
#define COUNTRY_MAX 10
#define MAX_COUNTRY_LENGTH 25
#define MAX_CAPITAL_LENGTH 25
typedef struct country
{
char cntName[MAX_COUNTRY_LENGTH];
char capName[MAX_CAPITAL_LENGTH];
double population;
}Country;
int ask(char * usrTxt);
int oSesame(char usrTxt[], FILE * pFile, Country * p[]);
promp.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "headers.h"
int ask(char * usrTxt)
{
int length;
printf("Enter text file to read from : ");
scanf("%s", usrTxt);
length = strlen(usrTxt);
}
int oSesame(char usrTxt[], FILE * pFile, Country * p[10])
{
int count = 0;
int savedOffset;
pFile = fopen(usrTxt, "rw");
if(pFile != NULL)
{
savedOffset = ftell(pFile); //save how far from beginning of file we start
fseek(pFile, 0, SEEK_END); //seek to end of file
if(ftell(pFile) == 0) //if end of file is same location as beginning then file is empty
{
printf("File %s is empty", usrTxt);
return 0; //end program
}
else{
fseek(pFile, savedOffset, SEEK_SET); //set location indicator to beginning to begin parsing
while(count<COUNTRY_MAX && !feof(pFile))
{
p[count] = (Country *) malloc(sizeof(Country)); //allocate memory for our structures since they havnt actually been declared yet just pointers to potential ones
fscanf(pFile, "%s[^\n]", p[count]->cntName); //read in as string until newline character found in regex
fscanf(pFile, "%s[^\n]", p[count]->capName);
fscanf(pFile, "%lf", &p[count]->population);
getc(pFile); //get new line character
count++;
}
fclose(pFile);
}
}
else
{
printf("Error opening %s , check your spelling and try again.\n", usrTxt);
}
return count;