Reputation: 29
I am trying to read in data from a text file, convert its contents into an integer, and finally store the integer values into a vector. However, I'm having an issue where the conversion skips the last number in the .txt file and seems to add a random value at the beginning of the vector when it goes to print it out.
For example, my test.txt file has the following values (Note: All of the values are put on its own line):
23
57
81
19
26
45
38
63
99
4
Here is my main.cpp:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
vector<int> myIntArray;
string line;
ifstream fileName("test.txt");
for(int number; getline(fileName, line, '\n'); number = stoi(line))
{
myIntArray.push_back(number);
cout << "Reading in number from the file: " << number << endl;
}
}
Once I run the program this is the output that I get:
Reading in number from the file: 28156
Reading in number from the file: 23
Reading in number from the file: 57
Reading in number from the file: 81
Reading in number from the file: 19
Reading in number from the file: 26
Reading in number from the file: 45
Reading in number from the file: 38
Reading in number from the file: 63
Reading in number from the file: 99
I'm not sure where that first number (28156) came from or why it skips the last number (4) in my test.txt file but this is the problem that I am having with my code.
Upvotes: 1
Views: 733
Reputation:
You can also construct the vector using an input iterator:
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
using namespace std;
ifstream f("test.txt");
vector<int> myIntArray(istream_iterator<int>(f), {});
for(auto i: myIntArray) {
cout << "Reading in number from the file: " << i << endl;
}
}
Upvotes: 3
Reputation: 1
You can simplify your loop like this:
for(int number; filename >> number;)
{
myIntArray.push_back(number);
cout << "Reading in number from the file: " << number << endl;
}
Upvotes: 3
Reputation: 75062
The 3rd part of for
loop (number = stoi(line)
in this case) is executed after executing the loop body.
Therefore, the 28156
is an indeterminate value of uninitialized non-static local variable and the last 4
is converted and discarded.
You have to do conversion before using number
like this:
for(int number; getline(fileName, line, '\n'); )
{
number = stoi(line);
myIntArray.push_back(number);
cout << "Reading in number from the file: " << number << endl;
}
Upvotes: 3