【问题标题】:Place ints from text file into an int array in C将文本文件中的整数放入 C 中的整数数组中
【发布时间】:2014-03-01 01:37:37
【问题描述】:

我正在阅读一个包含内容的文本文件:

2, 0, 15, 14, 24, 6, 19, 9, 25, 13, 7, 5, 21, 10, 12, 11, 4, 22, 23, 20, 17, 8, 18, 3, 1, 16

我想将每个单独的元素放入一个 int 数组中,然后打印该数组。我下面的代码给了我一个分段错误,但我无法解决这个问题。任何帮助都会很棒。

FILE *the_cipher_file;
the_cipher_file = fopen("cipher.txt", "r");
int * the_alphabet_array;
int size_of_alphabet;
int the_letter_counter = 0;

while(fscanf(the_cipher_file, "%d", &size_of_alphabet) > 0){
    the_alphabet_array[the_letter_counter] = size_of_alphabet;
    the_letter_counter++;
    printf("%d", size_of_alphabet);
}

【问题讨论】:

  • the_alphabet_array的定义是什么?
  • 1) 您在哪条线上遇到了段错误? 2)the_alphabet_array是如何定义的?
  • 您还需要将逗号扫描为字符。但需要查看更多代码以了解数组大小等。
  • 或者他可以显式地将逗号放入格式字符串中。空格也需要跳过。此格式字符串应该可以正常工作:" %d,".

标签: c arrays


【解决方案1】:

这是我以前写的一个简单程序,它很粗糙,但应该是你要找的,还要注意检查 *fp 是否为空。

我测试您的数据工作正常(只读取数字并跳过空格和逗号)。

2, 0, 15, 14, 24, 6, 19, 9, 25, 13, 7, 5, 21, 10, 12, 11, 4, 22, 23, 20, 17, 8, 18, 3, 1, 16    

#include <stdio.h>
int main(int argc, char *argv[]){

FILE *fp = fopen(argv[1],"r");
int array[100];
int size_of_alphabet =0;
int i =0;
while (fscanf(fp," %d%*[,] ",&size_of_alphabet)>0 && i<100) {
    array[i] = size_of_alphabet;
    printf("%d\n", size_of_alphabet);
    i++;

}
}

输入是 argv[1],所以用 ./a.out file_name.txt 运行程序

* 表示丢弃读取的内容,不要将其存储在输出变量中,因此在这种情况下它将丢弃逗号,[ 的详细信息可以在 scanf 或 fscanf 中找到手动的。大多数以“f”(打印格式化的东西)结尾的函数,比如 scanf 和 fscanf 都有类似的手册页。

使用 scanf 和 skipp 的东西 - http://classes.soe.ucsc.edu/cmps012a/Fall98/faq/scanfQ.html

fsacnf 手册页http://www.manpagez.com/man/3/fscanf/

有关扫描功能的有用信息。(小心缓冲区溢出)

scanf("%[^,]",array); // it expects characters(string) that don't contain commas,
                      // commas will be skipped. 

只读一个逗号会这样

scanf("%[,]",array); only commas will be read as a string

跳过逗号如下所示。

scanf("%d%*[,]",array); this one skips the comma if its after the number.

【讨论】:

  • 谢谢!这正是我想要做的。
【解决方案2】:

首先测试fopen是否成功,即the_cipher_file != NULL是否成功。

然后确保处理逗号 - 使用“%d”格式说明符扫描输入文件会读取数字序列并将其转换为整数值,但分隔符在输入缓冲区中仍未读取。您需要在下一次循环迭代再次应用“%d”转换之前跳过它...

【讨论】:

  • 如何将整数读入我的数组,但跳过逗号?
猜你喜欢
  • 1970-01-01
  • 2011-04-14
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
相关资源
最近更新 更多