c - 在 while 循环 C 外访问变量

标签 c variables while-loop

我是 C 的新手,所以请原谅这个愚蠢的问题。我有以下代码从文本文件中读取第 3 行,即数字 38。我在 while 循环内将其分配给一个 int,但是,在 while 循环外访问此变量时,我得到了不同的结果。这是我的代码:

int main() {

    FILE* file = fopen("blocks.txt", "r");
    char line[256];
    int number;
    int i = 0;
    while (fgets(line, sizeof(line), file)) {
        i++;
        if (i == 3)
        {
            number = line;

            //prints 38
            printf("%s", line);
        }
    }
    //prints something random!
    printf("%d", number);
    fclose(file);
    getchar();
    return 0;
}

抱歉,如果这是模糊的,它可能会被删除,但请给我一些帮助哈哈!

最佳答案

即使在第一次打印后,您的 while 循环仍会继续运行。并且 char 数组 linegets(line, sizeof(line), file) 行中不断更新。

#include <stdio.h>
#include <stdlib.h>

int main()
{

    FILE *file = fopen("blocks.txt", "r");
    char line[256];
    long int number;
    int i = 0;
    char *stopped;

    /*keeps updating line till fget returns a failed response*/
    while (fgets(line, sizeof(line), file))
    {
        i++;
        if (i == 3)
        {
            number = (int)strtol(line, &stopped, 10);
            if (!*stopped)
            { /* handle error */
                printf("Error in strtol\n");
                return -1;
            }
            //prints 38
            printf("%s", line);
        }
    }
    /*Once the while loop ends it will have the last 
    line of the file block.txt*/
    printf("%ld", number);
    fclose(file);
    getchar();
    return 0;
}

atoi 警告

我们本可以使用atoi。但是 atoi 并不安全,可能会导致许多粗心的错误。参见 link .您应该使用 strtol 将字符串转换为 long int

关于c - 在 while 循环 C 外访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54938221/

相关文章:

javascript - 如何在javascript中声明动态变量?

javascript - 无法在 addEventListener 函数之外获取视频持续时间

python - 输入不工作Python

c++ - 为 C++ 中的应用程序最佳使用而打开的并行套接字/TCP 连接数

c - 下面的表达式将如何在 C 中求值?

c++ - 具有最小依赖性的跨平台 C/C++ RabbitMQ 库

c - C 中的仅 header 和仅静态内联库

php - 避免在 PHP 中执行部分变量

mysql - 需要帮助在 VB.net 中编写一个循环以根据远程 sql db 中的用户名在 Windows 中创建文件夹

python - 使用嵌套循环在 while 循环中显示特定值?