为什么FSCANF可以用来首先在C中读取c?
我是C编程的新手。所以我也许有一个简单的问题。那么,为什么不能使用fscanf
无法使用fopen(读取模式)?我的意思是,据我了解,我必须首先使用fopen(写模式),然后fopen(读取模式)将起作用。如果我先在fopen(写模式)之前首先使用fopen(读取模式),则该代码在此代码中的工作状态不佳。另一件事是,为什么fscanf
无法在此代码中读取空间?我已经尝试了%*s
,而Fopen(读取模式)首先不起作用。
这是我的简单代码:
int main() {
FILE *fp;
fp = fopen("Test.txt", "r+");
char name[100], hobby[100];
int age;
fscanf(fp, "Name:%*s\nAge:%d\nHobby:%*s", &name, &age, &hobby);
printf("\nScan Result\n%s\n%d\n%s", name, age, hobby);
fclose(fp);
return 0;
}
test.txt 文件:
Name:This is a test
Age:21
Hobby:Play games
当我运行它时:
Scan Result
`░
0
>m
Process returned 0 (0x0) execution time : 0.016 s
Press any key to continue.
我错过了什么吗?还是不可能?回答给出的代码对我学习更好,谢谢。
I'm new to C programming. So I have maybe a simple question. So why fscanf
with fopen(read mode) can't be used? I mean, from what I learned I must use fopen(write mode) first so then fopen(read mode) will work. If i use fopen(read mode) first before fopen(write mode) it wouldn't work like in this code. Another thing is, why fscanf
can't read space in this code? I already tried %*s
while fopen(read mode) first and it didn't work.
Here is my simple code:
int main() {
FILE *fp;
fp = fopen("Test.txt", "r+");
char name[100], hobby[100];
int age;
fscanf(fp, "Name:%*s\nAge:%d\nHobby:%*s", &name, &age, &hobby);
printf("\nScan Result\n%s\n%d\n%s", name, age, hobby);
fclose(fp);
return 0;
}
Test.txt file:
Name:This is a test
Age:21
Hobby:Play games
When I run it:
Scan Result
`░
0
>m
Process returned 0 (0x0) execution time : 0.016 s
Press any key to continue.
So did I miss something? or it isn't possible? Answer with the code given would be very helpful for me to learn better, thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
%s
读取单个单词,使用%[^\ n]
读取所有内容,直到newline。扫描到字符串时,请勿在数组名称之前放置
&/code>。作为函数参数传递时,数组会自动衰减指针。
或使用
fgets()
一次读取一行,然后您可以使用sscanf()
从中提取。%s
reads a single word, use%[^\n]
to read everything until a newline.Don't put
&
before array names when scanning into a string. Arrays automatically decay to a pointer when passed as a function argument.Or use
fgets()
to read one line at a time, then you can usesscanf()
to extract from it.