如何检测“字符串数组”的结尾? (在c中)

发布于 2025-01-09 04:24:45 字数 387 浏览 0 评论 0原文

如果您对“字符串数组”感到困惑,它基本上是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哑剧 2025-01-16 04:24:45

只需检查 fgets() 的返回值并保留一个计数器,当您获得 NULL 指针时,(可能)没有更多内容可以从文件中读取。

   char array[10][10];
   FILE *fp = fopen ("file.txt","r");
   size_t max_size = sizeof(array) / sizeof(array[0]);
   size_t length = 0;


    while (length < max_size && fgets(array[length], sizeof(array[0]), fp) != NULL)
    {
        length++;
    }

   printf("%zu\n", length);
   fclose(fp);

但请注意,如果文件中的行数超过 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 a NULL pointer, there is (probably) nothing more to read from the file.

   char array[10][10];
   FILE *fp = fopen ("file.txt","r");
   size_t max_size = sizeof(array) / sizeof(array[0]);
   size_t length = 0;


    while (length < max_size && fgets(array[length], sizeof(array[0]), fp) != NULL)
    {
        length++;
    }

   printf("%zu\n", length);
   fclose(fp);

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 set errno 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文