输入文件:
Joe Smith 10 Main St. 555-1212我正在从具有上述格式的文件中读取记录,该文件包含由制表符分隔的3个字段,名称地址和电话号码。
while (fscanf(fp, "%s%s%s", rec[size].name, rec[size].address, rec[size].phone_number) != EOF) { size++; }我必须为第一个单词添加空格并忽略选项卡并开始阅读下一个字段。
Input file:
Joe Smith 10 Main St. 555-1212I'm reading a record from a file that has the above format which contains 3 fields, name address and phone number separated by tabs.
while (fscanf(fp, "%s%s%s", rec[size].name, rec[size].address, rec[size].phone_number) != EOF) { size++; }I have to include the white space for the first word and ignore the tabs and start reading the next field.
最满意答案
char buffer[4096]; int n; while (fgets(buffer, sizeof(buffer), fp) != 0) { if ((n = sscanf(buffer, "%[^\t] %[^\t] %[^\t\n]", rec[size].name, rec[size].address, rec[size].phone_number)) != 3) { if (n != EOF) fprintf(stderr, "Error: faulty record without 3 fields at:\n%s", buffer); break; } size++; }请注意,这使用fgets()来读取行。 它检查sscanf()读取三个字段。 你不应该得到n == EOF ,但测试以防万一。 错误消息在标准错误上报告,并包括导致问题的行( fgets()和sscanf()的主要优点之一是您为重试或错误报告捕获了行)。
char buffer[4096]; int n; while (fgets(buffer, sizeof(buffer), fp) != 0) { if ((n = sscanf(buffer, "%[^\t] %[^\t] %[^\t\n]", rec[size].name, rec[size].address, rec[size].phone_number)) != 3) { if (n != EOF) fprintf(stderr, "Error: faulty record without 3 fields at:\n%s", buffer); break; } size++; }Note that this uses fgets() to read lines. It checks that sscanf() read three fields. You should not get n == EOF, but test just in case. The error message is reported on standard error, and includes the line that caused the trouble (one of the major advantages of fgets() plus sscanf() is that you have the line captured for retries or error reporting).
更多推荐
发布评论