c - 从包含整数的文件中读取一行
问题描述
我需要从数据文件中读取以下内容:
Sabre Corporation 15790 West Henness Lane New Corio, New Mexico 65790
我的变量是char companyName[20+1]
, char companyAddress[30+1]
, char companyCity[15+1]
, char companyState[15+1]
, int companyZip
;
我使用 读取第一行companyName
就好了%[^\n]
,但尝试读取第二行相同,变量保持为空。
void getCompanyData(FILE *CompanyFile, char *companyName, char *companyAddress, char *companyCity, char *companyState, int *companyZip)
{
fscanf(CompanyFile,"%[^\n]%[^\n]%s%s%d", companyName, companyAddress, companyCity, companyState, companyZip);
}
当我运行此代码并打印出变量时,companyName
看起来很好,“Sabre Corporation”,但companyAddress
没有显示为任何内容。
如果我将第二个输入切换为简单%s
的,它会很好地读取地址的数字。
有没有办法像第一行一样将整行读取为一个变量,而不是将许多其他变量连接成一个更大的变量?
解决方案
来自 C 的一点翻译。
"%[^\n]%[^\n]%s%s%d"
%[^\n] // reads everything up to the new line
// But does not read the new line character.
// So there is still a new line character on the stream.
%[^\n]%[^\n] // So the first one reads up to the new line.
// The second one will immediately fail as there is a new line
// still on the stream and thus not read anything.
所以:
int count = scanf(CompanyFile,"%[^\n]%[^\n]%s%s%d", /*Variables*/ );
printf("Count = %d\n", count);
将打印 1,因为仅填充了一个变量。
我知道使用以下内容来阅读一行很诱人。
fscanf("%[^\n]\n", /* Variables*/ );
但这是一个坏主意,因为很难发现空行。空行不会将任何内容读取到变量中,因此在读取新行之前会失败,因此它实际上不会读取空行。所以最好把它分解成多个语句。
int count;
do {
count = fscanf("%[^\n]", /* Variables*/ );
fscanf("\n");
} while (count == 0);
// successfully read the company name and moved on to next line
// while skipping completely empty lines.
现在这似乎是上述内容的逻辑扩展。
但这不是最好的方法。如果您假设一行可能以前一行的“\n”开头(并且您想忽略数据行上的任何前导空格),那么您可以在前面使用一个空格。
int count = fscanf(" %[^\n]", /* Variables*/ );
// ^ The leading space will drop all white space characters.
// this includes new lines so if you expect the last read may
// have left the new line on the stream this will drop it.
另一件需要注意的是,您应该始终检查 a 的返回值,fscanf()
以确保实际扫描了您希望扫描的变量数量。