我是 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
数组 line
在 gets(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/