动态读取文件并创建整数数组

Read file and create integer array dynamically

本文关键字:整数 数组 创建 读取 文件 动态      更新时间:2023-10-16

这似乎是一项简单的任务,但到目前为止,我尝试过的所有方法都没有奏效。

我有一个文件foo.txt

3
3 4 2

现在我想读取这个文件,读取第一行并使用它在第一行读取的数字的大小实例化一个 int 数组。然后它应该用第二行中的元素填充该数组,该元素具有完全相同数量的元素,并在第一行中注明。

如果我们要给你示例代码,不妨告诉你最好的方法:

std::ifstream datafile("foo.txt");
if (!datafile) {
    std::cerr << "Could not open 'foo.txt', make sure it is in the correct directory." << std::endl;
    exit(-1);
}
int num_entries;
// this tests whether the number was gotten successfully
if (!(datafile >> num_entries)) {
    std::cerr << "The first item in the file must be the number of entries." << std::endl;
    exit(-1);
}
// here we range check the input... never trust that information from the user is reasonable!
if (num_entries < 0) {
    std::cerr << "Number of entries cannot be negative." << std::endl;
    exit(-2);
}
// here we allocate an array of the requested size.
// vector will take care of freeing the memory when we're done with it (the vector goes out of scope)
std::vector<int> ints(num_entries);
for( int i = 0; i < num_entries; ++i )
    // again, we'll check if there was any problem reading the numbers
    if (!(datafile >> ints[i])) {
        std::cerr << "Error reading entry #" << i << std::endl;
        exit(-3);
    }
}

演示(有小的更改,因为我无法在 ideone 上提供具有正确名称的文件):http://ideone.com/0vzPPN

你需要使用 ifstream 对象,就像使用 cin 一样

ifstream fin("foo.txt"); //open the file
if(!fin.fail()){
    int count;
    fin>>count; //read the count
    int *Arr = new int[count];
    for(int i=0;i<count;i++){ //read numbers
        fin>>Arr[i];
    }
    //... do what you need ...
    //... and finally ... 
    delete [] Arr;
} 

如果使用输入文件流打开文件,您可以简单地执行此操作:

std::ifstream file_txt("file.txt");
int number_count = 0;
file_txt >> number_count; // read '3' from first line
for (int number, i = 0; i < number_count; ++i) {
      file_txt >> number; // read other numbers
      // process number
}
文件流就像

其他标准流(std::cinstd::cout)一样,可以根据提供给operator>>的类型(在本例中为 int)应用格式。这适用于输入和输出。

或者,您可以通过简单地将其加载到std::vector中来避免事先读取大小的全部需求:

std::ifstream fin("myfile.txt"); 
std::vector<int> vec{std::istream_iterator<int>(fin), std::istream_iterator<int>()};
fin.close();

或者,如果无法使用 C++11 语法:

std::ifstream fin("myfile.txt");
std::vector<int> vec;
std::copy(std::istream_iterator<int>(fin), std::istream_iterator<int>(), std::back_inserter(vec));
fin.close();