如何检测“字符串数组”的结尾? (在c中)
如果您对“字符串数组”感到困惑,它基本上是 char arr[10][10];。我正在尝试使用“for”循环输入一个字符串数组,并且该字符串数组的长度未知(它是可变的)。如何编写一个“for”循环来知道该字符串数组的末尾在哪里并停止写入? (顺便说一句,如果您对我需要什么感到好奇,它适用于从文本文件中逐行读取字符串并将它们放入字符串数组中的系统)但是我可以检测到 EOF,所以现在我' m 使用 for 循环将行放入字符串数组中,并立即打印它......这里是:
fp = fopen ("file.txt","r");
for(i=0;!feof(fp);i++)
{
fgets(array[i],20,fp);
printf("\n%s",array[i]);
}
fclose(fp)
If you are confused with "Array of strings" it is basically char arr[10][10];
. I'm trying to type out an array of strings using 'for' loop, and the length of that array of strings is unknown (it's variable). How do I write a 'for' loop that would know where is the end of that array of strings and stop writing? (btw if you're curious as to what I'm needing, it is for a system that reads strings from a text file line by line and puts them in an array of strings) I can however detect EOF, so right now I'm using a for loop that puts lines in an array of strings, and immediately prints it... here it is:
fp = fopen ("file.txt","r");
for(i=0;!feof(fp);i++)
{
fgets(array[i],20,fp);
printf("\n%s",array[i]);
}
fclose(fp)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需检查
fgets()
的返回值并保留一个计数器,当您获得NULL
指针时,(可能)没有更多内容可以从文件中读取。但请注意,如果文件中的行数超过 10 行,则可能会超出范围。您还应该检查
length
是否在数组的范围内。fgets()
也会设置errno
来指示错误(如果您使用的是类似 POSIX 的系统)。另请参阅 为什么“while (!feof (file))”总是错误 和 < a href="https://faq.cprogramming.com/cgi-bin/smartfaq.cgi?id=1043284351&answer=1046476070" rel="nofollow noreferrer">为什么使用 feof() 控制循环不好。
Just check the return value of
fgets()
and keep a counter, when you get aNULL
pointer, there is (probably) nothing more to read from the file.But note that you might go out of bounds if it happens there are more than 10 lines in the file. You should also check that
length
is within the bounds of the array.fgets()
will also seterrno
to indicate the error, if you are on a POSIX-like system.Also, see Why is “while ( !feof (file) )” always wrong and Why it's bad to use feof() to control a loop.