Reputation: 1
I need to split a txt file into 2 arrays The txt file contains full number.Can I do it without string? For example,for input
4(how many line)
2 1
3 7
8 0
3 7
I want array 1 contains (firt number in a line)
{2
3
8
3}
array 2 contains (second number in a line)
{1
7
0
7}
How can I do that?Just curious...Here is a code which does not work..
ifstream ifs("sth.txt");
int g;
ifs>>g;
int girl[g];
int boy[g];
for(int i=0;i<2*g,i++;){
if (i%2==0)ifs>>gil[g];
if (i%2==1)ifs>>boy[g];}
cout<<boy[1];
Upvotes: 0
Views: 175
Reputation: 503
ifstream ifs("sth.txt");
int g;
ifs>>g;
int girl[g];
int boy[g];
for(int i=0;i<g,i++;){
ifs>>gil[i];
ifs>>boy[i];
}
cout<<boy[0];
or
int a =0; b = 0;
for(int i=0;i<g;i++){
if(i%2) ifs>>boy[b++];
else ifs>>girl[a++];
}
or
for(int i=1;i<=g;i+=2){
ifs>>boy[(i-1)/2];
if(i+1<=g)
ifs>>girl[(i-1)/2];
}
or
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
for(int i=0;i<g;i++){
fscanf(str,"%d %d",boy[i],girl[i]);
}
Upvotes: -1
Reputation: 3127
ifstream ifs("sth.txt");
int g;
ifs>>g;
int girl[g];
int boy[g];
for(int i=0;i<g,i++;){
ifs>>girl[i];
ifs>>boy[i];
}
cout<<boy[0];
You were reading to girl[g]
and boy[g]
instead of 0..(g-1)
.
I also changed reading: two ints insted of 1 in one iteration of the loop.
At the end I changed counting first (index 0) instead of second element of boy
.
Upvotes: 2