Hello,
I have written the same program using iostream, but now want to do it using fstream. Any STL container can be used.
I am trying to parse input from a file input.txt that contains:
List1 = 23, 30, 876, 24, 8934, 2131, 110, 437
List2 = 1, 3, 4, 6, 7
Output:
23
876
24
2131
110
I want to parse this file and store the content in 2 vectors, one vector for each list. Then print out the items in list1 in the order in list2.
List1 could have M elements, List2 could have N elements.
iostream version: Works like expected.
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 35 36 37 38 39
|
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> vec1;
vector<int> vec2;
int v1, v2, M, N;
cout << "insert the size of the first vector" << endl;
cin >> M;
for (int i = 0; i <M; i++) {
cout << "insert a value to be inserted in the first vector" << endl;
cin >> v1;
vec1.push_back(v1);
}
cout << "insert the size of the second vector" << endl;
cin >> N;
for (int i = 0; i <N; i++) {
cout << "insert a value to be inserted in the second vector" << endl;
cin >> v2;
vec2.push_back(v2);
}
for (int i = 0; i < vec2.size(); i++) {
int x = vec2[i];
cout << vec1[x]<< endl;
}
return 0;
}
|
Fstream: This is where I am at :(
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
|
#include <fstream>
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <cstdlib>
using namespace std;
int main() {
ifstream myfile;
vector<string> vec1;
string input_string1;
myfile.open("input.txt");
if (myfile.is_open()) {
int index1 = input_string1.find_first_of("=");
input_string1 = input_string1.substr(index1 + 1);
stringstream ss(input_string1);
while(ss.good()) {
std::string substring;
std::getline(ss, substring, ',');
vec1.push_back(std::atoi(substring));
}
}
myfile.close();
return 0;
}
|
Thank you,