Importing data from a text file

Hi! I need to fulfill an array with the data imported from a text file! Is there a way? Say that I have an array of five strings, and a text file like this:

ABC DEF GHI JKL MNO"

How could I do that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>
#include <string>
#include <vector>

int main()
{
    std::vector<std::string> words;
    if(std::ifstream in {"filename.txt"})
    {
        std::string word;
        while(in >> word)
        {
            words.push_back(word);
        }
    }
    else
    {
        //couldn't open file
    }
}
Last edited on
@LB:
Are you sure about line 8 and 11? I copied your code in my compiler (I use Code::Blocks) and I received these errors:

// Line 8: error: expected primary expression before 'in'
// Line 8: error: expected ')' before 'in'
// Line 11: error: 'in' was not declared in this scope
Oops, change line 8 to use curly braces: if(std::ifstream in {"filename.txt"})
Oh, thank you!

I'm not yet acquainted with "ifstream" class, so could you please briefly explain the code to me? In the line 8, you used 'in' as though it is a boolean function and in code 11 it is used in a different syntax. What does it mean? Why we need "word" string?
std::ifstream is C++'s standard input file stream. You can learn about file streams from the tutorial on this site:
http://www.cplusplus.com/doc/tutorial/files/
The tutorial is slightly outdated - for example, you almost never need to use .open() or .close().

Kreadeth wrote:
In the line 8, you used 'in' as though it is a boolean function and in code 11 it is used in a different syntax. What does it mean?
This is how all C++ stream classes work - all C++ streams are implicitly convertible to boolean type, and they all support the formatted extraction/insertion operators (depending on whether they are an input stream or output stream, of course).

On line 8, I both construct the stream and convert it to boolean to check if it is valid to use. If something went wrong with opening the file, the code will go to the else branch.

On line 11 I just use the formatted extraction operator the same way I would with std::cin. In C++ it is proper to loop on the input operation. When the input operation fails, the stream's implicit boolean becomes false and ends the while loop.

Kreadeth wrote:
Why we need "word" string?
It is just a temporary variable - we cannot directly take from a string and add to a vector, we need the temporary variable.
Thanks a lot, I appreciate it.
Topic archived. No new replies allowed.