[英]Error in printing output when using fscanf in C
這是我一直在研究 C 的代碼。
char Host_ip[256];
char *Database_name;
char *Username;
int listen_port;
FILE *myfile = fopen("Coin_Converter.config", "r");
fscanf(myfile, "Host=%s Database=%s Username=%s listenport=%d", Host_ip, Database_name,
Username, &listen_port);
fclose(myfile);
printf("Host = %s", Host_ip);
printf("Username= %s", Username);
printf("Database= %s", Database_name);
printf("listenport = %d", listen_port);
我的配置文件如下所示:
Host = 127.0.0.1
Database = base20
Username = John
listenport = 8080
我對編譯代碼沒有任何問題,但我無法打印任何內容。 事實上,當我只打印 Host_ip 時它正在工作,但否則我什么也沒有得到。 我嘗試了幾件事,但我無法弄清楚我做錯了什么。
代碼中的兩個主要錯誤是
使用未分配的指針而不是緩沖區
不過濾輸入流中的空格。
通過一些更改(注釋),代碼變為
#include <stdio.h>
int main()
{
char Host_ip[256];
char Database_name[256]; // array instead of pointer
char Username[256]; // array instead of pointer
int listen_port;
FILE *myfile = fopen("Coin_Converter.txt", "r");
if(myfile == NULL)
return 1;
fscanf(myfile, "Host = %255s Database = %255s Username = %255s listenport = %d",
Host_ip, Database_name, Username, &listen_port); // added spaces
fclose(myfile);
printf("Host = %s\n", Host_ip); // added newlines
printf("Username= %s\n", Username);
printf("Database= %s\n", Database_name);
printf("listenport = %d\n", listen_port);
}
和輸出
Host = 127.0.0.1
Username= John
Database= base20
listenport = 8080
fscanf
格式字符串中添加的空格是為了從輸入流中刪除任何空格(或沒有空格)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.