Vectors in .txt files

How can I write a vector inside a .txt file?
You cannot,

unless you mean write a vector to a text file. In that case, you do it the same way you would write anything else to a text file.
Thanks for the quick answer!

Yes, sorry for my english. I was trying to express what you meant. And how would that be? I mean, something like this?

int vector;
ofstream myfile;

for(i = 0; i < 4; i ++) {
.....myfile << vector[i] << endl;
}

And then, how could I read a .txt file and save the data in a vector?
Last edited on
That is pretty much it, except if would be better to use i < vector.size() instead of a magic number.

The reverse is the same, again, except a while loop is better since you probably wont know ahead of time how many elements there are.
You can do something like this:

1
2
3
4
5
6
7
8
9
10
11
ifstream fileName;
fileName.open("file.txt");

string data; // it could be int, or any data type you want
vector<string>myVec;  // if you data type is 'int', do replace <string> with <int>

while (!file.eof()) // loop until end of file
{
   fileName >> data;
   myVec.pushback(data);
}

This is the simplest way to read from file and store data in vector.

Tip: Do not forget to #include <vector> before your main

Hope this helps!
@newbiee999: Your read on line 9 can fail. Therefore:
1
2
3
while ( fileName >> data ) {
   myVec.pushback( data );
}
PART 1

That is pretty much it, ...

And vector is a type name - not a variable name.

(Or did you mean that "vector" was an array of int? e.g. int vector[4]; ?? If so, it's a confusing name to use as it's the name of a standard C++ container class -- std::vector.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

// etc

vector<int> myVector; // for example

// add some value to vector

ofstream myfile("file.txt");
// check it opened OK

for(int i = 0; i < myVector.size(); i++) {
.....myfile << myVector[i] << endl;
}

// Etc 


PART 2

You can do something like this: ...

You shouldn't really use fstream::eof() to control a read loop!!

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 <string>
#include <vector>
using namespace std;

int main()
{
    // It's better form to use constructor that opens file
    // rather than the default constructor followed by open
    // method. Destructor calls close(), of course.
    ifstream fileIn("file.txt"); // fileName is not a good name for a file!
    if(!fileIn.is_open())
    {
        cout << "Failed to open file!\n";
        return 0;
    }

    string data;           // it could be int, or any data type you want
    vector<string> myVec;  // if you data type is 'int', do replace <string> with <int>

    // operator>> returns a reference to the fstream which
    // can be tested using if(), etc to see if its state is still good
    // (this checks not only for eof() but also error conditions.
    while (fileIn >> data) // loop until no more input or error
    {
        // and remember operator>> can only extract string without spaces!
        myVec.push_back(data);
    }

    // Etc (could check for eof() here to confirm whole file was processed.)

    return 0;
}


See (e.g.) the C++ FAQ for further info...

Input/output via <iostream> and <cstdio>
https://isocpp.org/wiki/faq/input-output

Esp.

Why does my input seem to process past the end of file?
https://isocpp.org/wiki/faq/input-output#istream-and-eof

How does that funky while (std::cin >> foo) syntax work?
https://isocpp.org/wiki/faq/input-output#istream-and-while

Andy
Last edited on
Thank you all for those answers! Now it's time for me to use those pieces of codes :D
By the way... What's the difference between 'ifstream' and 'ofstream'?
ifstream is input file stream. {Use it to get data from a file}
ofstream is output file stream. { Use it to output data to a file}

Ok, thanks! Now I have another question... I wrote some data to a file, but every time I run the program it erases the content of the file and writes new data.

I've already tried with FILE *ยจ, but I can't figure out how to use fwrite or fprintf correctly... Can you explain to me with a piece of code, how you'd write the data of a string vector to a file?

O better, without using FILE *, how can I write data to a file, without erasing what it was already written in it?
It's simple!
When you open the file do this:
1
2
3
4
ofstream myFile;
myFile.open("data.txt", fstream::app); // by opening it with this statement, any data you write
                                  // to the file will be appended to the file instead of overwriting
Last edited on
THANKS! IT WORKED!
And now, I have another question...

Let's supose I have: vector<string> nombres;
And then, the user introduces a name: cin >> nombre;
How can I check inmediately if that is inside the vector?

I'm looking for something like in Python, in which we only write: if(nombre in nombres): ...

Something like that, is it possible?

And, another thing, how can I show the content of a txt file in the console, directly as it is in the file?
Last edited on
I'm looking for something like in Python, in which we only write: if(nombre in nombres): ...


Because algorithms are generalized to work with iterators instead of containers, it's a little more verbose in C++:

1
2
3
4
5
6
7
8
9
10
#include <algorithm>

// ...

    if ( std::find(nombres.begin(), nombres.end(), nombre) != nombres.end() )
    {
        // ...
    }

// ... 


And, another thing, how can I show the content of a txt file in the console, directly as it is in the file?

You should be able to figure this out on your own. Get a line, output a line.

Btw, new questions unrelated to original topic/question should be asked in a new thread.
Ok, thanks
Topic archived. No new replies allowed.