问题
I'm making a program that reads only integers from text file. I want to make a function that reads integers and stores them in an array so I can use that array later to sort them with bubble sort. This is what I have so far but the output I get is some random -803234.... number :
void read(int A[max], int& numbers) {
ifstream file("ints.txt");
if (file.is_open()) {
file >> numbers;
for (int i = 0; i < numbers; i++) {
cout << "numbers: " << A[i] << endl;
}
file.close();
}
cout << "numbers in array: " << A[numbers] << endl;
}
回答1:
You don't store the numbers in the array at any point:
void read(int A[max], int& numbers) {
ifstream file("ints.txt");
if (file.is_open()) {
file >> numbers;
for (int i = 0; i < numbers; i++) {
// you're printing A[i] but you haven't stored
// anything there.
cout << "numbers: " << A[i] << endl;
I assume that numbers
is the number of entries in the file and that you intended to read the values the same way you read numbers
but into A[i].
cin >> A[i];
The last part of your code also tries to print beyond the last entry of the array:
cout << "numbers in array: " << A[numbers] << endl;
Remember, C++ arrays are 0 based, so A[numbers]
is the *numbers + 1*th entry.
回答2:
std::vector<int> read_ints(std::istream& is)
{
std::vector<int> result;
std::copy(std::istream_iterator<int>(is),
std::istream_iterator<int>(),
std::back_inserter(result));
return result;
}
If you can't use vectors, you've got a problem because you now need to check for end of file and for running out of space in your array...
this function will check for both, and return the number of integers that have been placed into the buffer:
template<size_t N>
size_t read_ints(int (&dest)[N], std::istream& is)
{
size_t i = 0;
while (i < N && is >> dest[i]) {
++i;
}
return i;
}
non-template version:
#define BUFFER_LEN 100
size_t read_ints(int (&dest)[BUFFER_LEN], std::istream& is)
{
size_t i = 0;
while (i < BUFFER_LEN && is >> dest[i]) {
++i;
}
return i;
}
来源:https://stackoverflow.com/questions/35900988/c-read-integers-from-file-and-save-into-array