从 stdin 重定向文件,使用 fgets() 将信息读取到数组
Redirecting a file from stdin, using fgets() to read information to array
int main() {
#define MEMSIZE 100
int memory[MEMSIZE] = {0};
int i = 0;
char *temp = malloc(sizeof(100));
fgets(temp, MEMSIZE, stdin);
for (i = 0; i < (sizeof(memory)/sizeof(int)); i++) {
memory[i] = temp[i];
}
for (n = 0; n < 10; n++) { // Print contents
printf("%d - %d\n", n, memory[n]);
}
}
所以今天我有一个看起来很简单的问题。我正在从 stdin 获取文件,使用:
./a.out < filename
我的主要目标是获取文件中提供的数字,并将它们存储到一维数组中。我当前使用的 fgets()
工作正常,读取第一行并将这些元素复制到我的一维数组中(它们的 ASCII 值转换为 int)。现在,要读取我的下一行,如果我再次调用 fgets()
,将读取下一行,但它会存储在与第一个值相同的位置,从而在我的数组中的位置 0-3 中覆盖它们。这些值需要连续存储在我的数组中,直到 EOF。
文件格式为:
1234
5678
...
#include <stdio.h>
#define MEMSIZE 100
int main() {
int memory[MEMSIZE] = {0};
int i,n;
for (i = 0; i <MEMSIZE; i++){
if(fscanf(stdin,"%d", (memory+i))==EOF){
break;
}
}
//i is the number of ints you got
for (n = 0; n < i; n++) { // Print contents
printf("%d - %d\n", n, memory[n]);
}
return 0;
}
我看不出有理由在这里使用动态分配作为临时变量。
如果文件是数字列表,只读为数字,这里不需要fgets
,如果你还想把它读为字符串,看看atoi
函数
sizeof(memory)/sizeof(int)
=(sizeof(int)*MEMSIZE)/sizeof(int)
=MEMSIZE
你不应该只循环 MEMSIZE
次,你需要知道什么时候循环 EOF
我不知道你为什么在打印循环中假设 10 就足够了,我将其更改为 i
这是元素的数量
你没有定义n
希望对您有所帮助。
int main() {
#define MEMSIZE 100
int memory[MEMSIZE] = {0};
int i = 0;
char *temp = malloc(sizeof(100));
fgets(temp, MEMSIZE, stdin);
for (i = 0; i < (sizeof(memory)/sizeof(int)); i++) {
memory[i] = temp[i];
}
for (n = 0; n < 10; n++) { // Print contents
printf("%d - %d\n", n, memory[n]);
}
}
所以今天我有一个看起来很简单的问题。我正在从 stdin 获取文件,使用:
./a.out < filename
我的主要目标是获取文件中提供的数字,并将它们存储到一维数组中。我当前使用的 fgets()
工作正常,读取第一行并将这些元素复制到我的一维数组中(它们的 ASCII 值转换为 int)。现在,要读取我的下一行,如果我再次调用 fgets()
,将读取下一行,但它会存储在与第一个值相同的位置,从而在我的数组中的位置 0-3 中覆盖它们。这些值需要连续存储在我的数组中,直到 EOF。
文件格式为:
1234
5678
...
#include <stdio.h>
#define MEMSIZE 100
int main() {
int memory[MEMSIZE] = {0};
int i,n;
for (i = 0; i <MEMSIZE; i++){
if(fscanf(stdin,"%d", (memory+i))==EOF){
break;
}
}
//i is the number of ints you got
for (n = 0; n < i; n++) { // Print contents
printf("%d - %d\n", n, memory[n]);
}
return 0;
}
我看不出有理由在这里使用动态分配作为临时变量。
如果文件是数字列表,只读为数字,这里不需要
fgets
,如果你还想把它读为字符串,看看atoi
函数sizeof(memory)/sizeof(int)
=(sizeof(int)*MEMSIZE)/sizeof(int)
=MEMSIZE
你不应该只循环
MEMSIZE
次,你需要知道什么时候循环EOF
我不知道你为什么在打印循环中假设 10 就足够了,我将其更改为
i
这是元素的数量你没有定义
n
希望对您有所帮助。