Hello, so i have a problem here. I am trying to read file that looks like this:
dont try to read words, you wont get them.
Pavardenis Vardenis, Kova, 1992 puolejas, 6 8 9 11
Petraitis Petras, Kova, 1993 vartininkas, 10 5 3
Jonaitis Jonas, Kova, 1994 gynejas, 4 7 8
Kestutis Kestas, Vartai, 1984 vartininkas, 12 13 14 10
Tomaitis Tomas, Vartai, 1985 puolejas, 8 6 10
Juozaitis Juozas, Vartai, 1990 gynejas, 7 1 2 3
Rokaitis Rokas, Taure, 1989 gynejas, 5 4 2
Ignaitis Ignas, Taure, 1988 puolejas, 9 8 7 15
Vytaitis Vytautas, Taure, 1991 vartininkas, 5 9 7
At the end of each line, there are random ammount of numbers, how can i read them ? I want to place them to massive, like a[i] = number;
everything i tried doesnt work - string takes only one digit of number, leaving it from 0 to 9.
I presume that "massive" means static array. No, you don't want static array. Vector is nice.
1. You read one whole line into string.
2. You construct an istringstream from the string.
3. You read everything up to first comma from the stream.
4. You read everything up to second comma.
5. You read everything up to third comma.
6. While stream has integer, push it into vector.
Steps 1,3-5 use the string-version of std::getline
Step 6 uses formatted stream input
#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
int main()
{
string field1, field2, field3;
vector<int> nums;
int num;
while (cin.good()) {
getline(cin,field1, ','); // read up to first comma
getline(cin,field2, ',');
getline(cin,field3, ',');
// Now read the numbers until you fail. This assumes that
// the first word on the next line does NOT start with a digit
while (cin >> num) {
nums.push_back(num);
}
// Print out what you've read:
cout << field1 << " | "<< field2 << " | "<< field3 << " | ";
for (int i=0; i<nums.size(); ++i) {
cout << nums[i] << ",";
}
cout << '\n';
// Clean up for the next round
nums.clear();
// When the program failed to read the last number, the failbit
// was set on cin. Clear it now. Note that with this usage,
// cin.clear() would make more sense if named cin.setstate():
cin.clear(cin.rdstate() & ~ios::failbit);
}
}