Reading different things from textfile

I want to read both a string and an integer from a file.

This is the general format of the file:
String String (arbitrary length and numbers of strings) | Integer

First, is is easier/better if the format is different. So something like this:
String String Integer

Please advice on whichever is easier to read from.

My main questions however is how to read the integer value in the string separate from the strings so I can store and use them.


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
26
27
28
29
30
31
32
33
34
#include <iostream> 
#include <fstream>
#include <vector>
#include <string>

int main(int argc, char const *argv[])
{
	using namespace std;
	std::vector<string> names;
	std::vector<int> percentages;
	string myfile, line;
	cout << "filename: ";
	cin >> myfile;

	ifstream file (myfile + ".txt");
	if (file.is_open())
	{
		while(getline(file, line)){
			names.push_back(line);
		}
		/* 
			This is where I want to read and pushback integers to the
			percentages vector, from the same textfile as names.
		*/
	}
	else{
		cout << "No such file exists" << endl;
	}

	for(string s : names){
		cout << s << endl;
	}
	return 0;
}
Read each word from the line into a vector, and then the last element of the vector will be the integer in string format.
First, is is easier/better if the format is different.

How about
Integer String String String....
Then you can read each line with
while ((cin >> num) && getline(cin, line)) {...
Then you can read each line with

Is the order of the operations specified by the standard?
Yes, it has to work that way because of short circuit evaluation.
good to know, I allways wondered if it works like that but I was allways to lazy to look it up...
Topic archived. No new replies allowed.