Use pushback method to add data from a file to a vector

Nov 5, 2019 at 6:40am
closed account (jEb91hU5)
I'm trying to add data to a vector using the pushback method. It is giving me an error when trying to run that I don't quite understand.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
using namespace std;

void main()
{
	vector<int> intList;
	int myint;
	ifstream inf("vec.dat");
	while (!inf.eof())
	{
		inf >> myint;
		intList.push_back(inf.get());
		cout << intList[myint] << endl;
		myint++;
	}
	
	system("pause");
}


The data file is just a bunch of integers.
ex.

26  19  45  3  82  123  22 51  30  87  74
Nov 5, 2019 at 6:55am
It is giving me an error when trying to run that I don't quite understand.
What is the error?

Copy'n'paste the error text.


The error is misread file data.
Last edited on Nov 5, 2019 at 7:09am
Nov 5, 2019 at 7:06am
std::istream::get reads a single character from a file, not an int. You are misreading the data in your file. That is your error.

http://www.cplusplus.com/reference/istream/istream/get/

A few fixes are needed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
#include <vector>

int main()
{
   std::vector<int> vec;

   std::ifstream fin("vec.dat");

   int vec_int { };

   while (fin >> vec_int) { vec.push_back(vec_int); }

   std::cout << "Read from the file:\n";

   for (const auto& itr : vec) { std::cout << itr << ' '; } std::cout << '\n';
}

Read from the file:
26 19 45 3 82 123 22 51 30 87 74
Last edited on Nov 5, 2019 at 7:23am
Nov 5, 2019 at 7:10am
closed account (jEb91hU5)
It won't let me copy and paste. The error says:

Debug Assertion Failed!

Program: C:\Users ......
Line: 1455

Expression: Vector subscript out of range

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)


Then gives me the option to Abort, Retry, or Ignore
Last edited on Nov 5, 2019 at 7:10am
Nov 5, 2019 at 7:19am
VS does allow for copy'n'paste of error text from the IDE. Just highlight the text and right-click. Select "Copy" or press CTRL+C.

Severity Code Description Project File Line Suppression State
Error C2143 syntax error: missing ';' before 'for' Project1 C:\Programming\My Projects 2019\Project1\Project1\Source.cpp 20
Error (active) E0065 expected a ';' Project1 C:\Programming\My Projects 2019\Project1\Project1\Source.cpp 20

Your error is a run-time error. That is one serious problem. Fixable using the proper way to read data from your file.

BTW, modern C++ requires main to return int, not void.

Nov 5, 2019 at 9:13am
Line: 1455


Seriously?
Topic archived. No new replies allowed.