gpt4 book ai didi

c - 从c中的文件中读取字符串

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:30 26 4
gpt4 key购买 nike

我有一个这样的输入文件:

1 2 2 Medium 
1 2 0 Medium
2 1 0 Medium
2 0 2 Medium

我正在使用 fscanf() 读取整数值并且工作正常。有没有人知道如何读取字符串并将其放在字符串变量中???

int x,y,z; 
char* cs;
fscanf(fp3,"%d",&x);
fscanf(fp3,"%d",&y);
fscanf(fp3,"%d",&z);
fscanf(fp3,"%s",&cs);

最佳答案

您需要已经分配的空间来存储字符串。尝试这样的事情:

int x,y,z; 
char cs[20];
fscanf(fp3,"%d",&x);
fscanf(fp3,"%d",&y);
fscanf(fp3,"%d",&z);
fscanf(fp3,"%19s",cs);

您还可以一次扫描所有值:

fscanf(fp3,"%d %d %d %19s", &x, &y, &z, cs);

注意:始终使用 %<length>s在 scanf 模式中以防止缓冲区溢出。

关于c - 从c中的文件中读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15172209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com