-2

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

我有一个文件foo.txt

3
3 4 2

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

4

4 回答 4

2

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

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

于 2013-10-24T15:55:45.867 回答
0

或者,您可以通过简单地将其加载到 a 中来避免预先读取大小的全部需要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();
于 2013-10-24T16:00:25.373 回答
0

您需要像使用 cin 一样使用 ifstream 对象

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;
} 
于 2013-10-24T15:51:17.767 回答
0

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

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::cin, std::cout)一样可以根据提供给operator>>(在本例中为int)的类型应用格式。这适用于输入和输出。

于 2013-10-24T15:51:56.617 回答