Hello i need an algorithm to do the following:
I have a text file:
5 32
1 23
And i want to save each number in array but the first column in one array and the second column in second array
e.g array1 = 5, 1
array2 = 32, 23
Thanks.
7 replies to this topic
#1
Posted 08 August 2011 - 06:38 AM
|
|
|
#2
Posted 08 August 2011 - 09:50 AM
What do you have so far? Where are you stuck?
#3
Posted 08 August 2011 - 11:22 AM
It could look like this:
Look here for further information.
Greets,
artificial
#include <stdio.h>
#define LENGTH_OF_FILE 2
int main(int argc, char* argv[])
{
int array1[LENGTH_OF_FILE];
int array2[LENGTH_OF_FILE];
FILE* ptrFile = fopen("File.txt", "r");
for(int a = 0; a < LENGTH_OF_FILE; a++)
{
fscanf(ptrFile, "%d %d", &array1[a], &array2[a]);
}
fclose(ptrFile);
return 0;
}
Look here for further information.
Greets,
artificial
Sometimes words ain't enough to express something. That's why computer scientists use double words.
#4
Posted 08 August 2011 - 11:01 PM
I forget to say that my program is C++.
here is my code of reading full line
here is my code of reading full line
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream input ("input.txt", ios::in);
ofstream output("output.txt", ios::out);
int x;
while(!input.eof())
{
input >> x;
}
input.close();
return 0;}
#5
Posted 08 August 2011 - 11:37 PM
But C code should work fine under C++, shouldn't it?
I think the scanf() method should work.
I think the scanf() method should work.
#6
Posted 09 August 2011 - 04:10 AM
Only the include should be a little different. I think it's cstdio.h.
#7
Posted 09 August 2011 - 10:58 AM
No, and no.
Here's a way to do this, and the only real issue is that you're not putting it into an array yet. O_o
Hmm... I think that should work. :P
Here's a way to do this, and the only real issue is that you're not putting it into an array yet. O_o
while (!input.eof())
{
while (input)
{
// I do these getline antics to ensure that the input is PER LINE rather than
// just a bunch of ints in a row.
std::string str;
getline(input, str);
std::stringstream strm(str);
// Then we extract the formatted data (so we don't have to parse it on our own)
strm >> x;
first_vector.push_back(x);
if (input)
{
// Yes, another painful if statement to make sure the last formatted extraction
// didn't fail.
strm >> x;
second_vector.push_back(x);
}
}
if (input.fail())
{
input.clear(std::ios_base::failbit);
std::cerr << "Bad input format on line " << line_num;
}
}
Hmm... I think that should work. :P
Wow I changed my sig!
#8
Posted 09 August 2011 - 11:30 PM
Ok thanks :)
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account

Back to top









