c语言中fgets和sscanf
作者:野牛程序员:2023-11-23 14:52:06C语言阅读 2997
fgets用于从文件流中读取一行字符串,而sscanf用于按照指定的格式从字符串中读取数据。fgets从文件中读取一行,包括换行符,然后将其存储为一个字符串。另一方面,sscanf根据指定的格式字符串从字符串中读取数据,并将其存储到指定的变量中。
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r"); // 打开文件用于读取
char buffer[100];
if (file != NULL) {
// 使用fgets从文件中读取一行
if (fgets(buffer, sizeof(buffer), file) != NULL) {
// 处理读取到的字符串
printf("Read from file: %s", buffer);
// 使用sscanf从字符串中读取数据
int intValue;
float floatValue;
char stringValue[50];
sscanf(buffer, "%d %f %s", &intValue, &floatValue, stringValue);
// 处理读取到的数据
printf("Parsed values: %d, %.2f, %s\\n", intValue, floatValue, stringValue);
} else {
printf("Failed to read from file.\\n");
}
// 关闭文件
fclose(file);
} else {
printf("Failed to open file.\\n");
}
return 0;
}上面的示例代码假设文件 "example.txt" 中包含一行类似于 "42 3.14 Hello" 的内容。fgets用于从文件中读取整行,然后sscanf用于按照指定的格式解析该行的内容并将其存储到相应的变量中。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

