C语言fscanf函数提取空格分隔的两个数字
您可以使用fscanf函数按照指定的格式从文档中读取数据,并将数据分别保存到两个变量中。以下是一个示例代码:
#include <stdio.h>
int main() {
FILE *file;
int number1, number2;
// 打开文件
file = fopen("data.txt", "r");
if (file == NULL) {
printf("无法打开文件。\n");
return 1;
}
// 使用fscanf读取数据
fscanf(file, "%d %d", &number1, &number2);
// 输出读取的数据
printf("第一个数字:%d\n", number1);
printf("第二个数字:%d\n", number2);
// 关闭文件
fclose(file);
return 0;
}
在上面的代码中,我们假设要读取的数据存储在名为"data.txt"的文件中。首先,我们使用fopen函数打开文件,然后使用fscanf函数按照"%d %d"的格式读取两个整数,并将它们分别保存到number1和number2变量中。最后,我们输出读取的数据,并使用fclose函数关闭文件。
请注意,上述代码中的文件路径是相对路径,您需要根据实际情况修改为正确的文件路径。
原文地址: https://www.cveoy.top/t/topic/pvNa 著作权归作者所有。请勿转载和采集!