Reading numbers from a file into an Array/Vector

Hi had a question about reading a file with a int and a string and putting it into a vector/array

The file is called options.txt and contains:

5000 Leather Seats
1000 DVD System
800 10 Speakers
1400 Navigation System
500 CarPlay
500 Android Auto
2000 Lane Monitoring
800 3/36 Warranty
999 6/72 Warranty
1500 Dual Climate
225 Body Side Molding
49 Cargo Net
87 Cargo Organizer
700 450W Audio
1000 Heated Seats


I'm separating the prices and the options into their own vectors/arrays however I don't know how to process the whitespace between prices and options (also don't know how to include spaces for the options such as Cargo Net).
Last edited on
<< splits out whitespace for you.
so
file >> intvariable;
will read the integer.
but your input is complex with additional white space and terms for some data.
what do you want here, is it integer & one string ?
Int being price or for example 1000 or 700 <- only int

String being name of component like "Cargo Net" or "450W Audio" <- with whitespace for the component included

These all need to be their own array/vector

So in theory, one string array/vector for the parts and one int array/vector for the prices
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct data
{
  string s;
  int i;	
};
int main ()
{
   vector<data> d;   
   data tmp;
   ifstream ifs("dat");
   while(ifs >> tmp.i)
   {
	 getline(ifs,tmp.s);
     d.push_back(tmp);	 
   }
   for(auto &a : d)
	   cout << a.i << " | " << a.s << endl;
}



5000 |  Leather Seats
1000 |  DVD System
800 |  10 Speakers
1400 |  Navigation System
500 |  CarPlay
500 |  Android Auto
2000 |  Lane Monitoring
800 |  3/36 Warranty
999 |  6/72 Warranty
1500 |  Dual Climate
225 |  Body Side Molding
49 |  Cargo Net
87 |  Cargo Organizer
700 |  450W Audio
1000 |  Heated Seats


Note that mixing stream (>> and <<) with getline can be error prone. I believe I did it right here, but always double check that when you mix these tools. If you do not trust the file, you could add error checking ...
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
#include <iterator>

struct Data {
	std::string s;
	int i {};
};

int main() {
	std::ifstream ifs("data.txt");

	if (!ifs)
		return (std::cout << "Cannot open file\n"), 1;

	std::vector<Data> opts;

	for (Data d; (ifs >> d.i) && std::getline(ifs >> std::ws, d.s); opts.push_back(std::move(d)));

	for (const auto& a : opts)
		std::cout << a.i << " | " << a.s << '\n';
}



5000 | Leather Seats
1000 | DVD System
800 | 10 Speakers
1400 | Navigation System
500 | CarPlay
500 | Android Auto
2000 | Lane Monitoring
800 | 3/36 Warranty
999 | 6/72 Warranty
1500 | Dual Climate
225 | Body Side Molding
49 | Cargo Net
87 | Cargo Organizer
700 | 450W Audio
1000 | Heated Seats

Last edited on
Topic archived. No new replies allowed.