Have multiple lines in one string (Read function)

closed account (4i67ko23)
Hi there,,
I've made this function:
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
#include <algorithm>
#include <iostream>
#include <fstream>
#include <string>
//-----------------------------------------------------------
using namespace std;
//-----------------------------------------------------------
string readfile(string IN_FILE_NAME)
{ 
    string EX_FILE_TEXT;
    ifstream FILE (IN_FILE_NAME.c_str());
    if (FILE.is_open())
    {
        while ( FILE.good() )
        {
            getline (FILE,EX_FILE_TEXT);
            cout << EX_FILE_TEXT << endl;
        }
        FILE.close();
    }
    else cout << "[Error - 001] Can't open "<< IN_FILE_NAME <<endl;
    return (EX_FILE_TEXT);
}
//-----------------------------------------------------------
int main()
{
    //writefile("TEST123", "mathijs_text_1");//1
    //readfile("abc123.txt");
    cout << readfile("file.txt") << endl;
    Sleep(10000);
}

It prints 4x abc123.
In file.txt is 3x abc123 writed. In line 17, it prints 3x abc123, this must be, while in line 29 it only prints abc123 1 time. How can I edit this?

MathijsS
Last edited on
1
2
while( getline (FILE,EX_FILE_TEXT) )
   cout << EX_FILE_TEXT << endl;

The file was good, the read failed but you still output it.
closed account (4i67ko23)
Must it be like this?
1
2
3
4
5
6
7
8
9
10
11
12
string readfile(string IN_FILE_NAME)
{ 
    string EX_FILE_TEXT;
    ifstream FILE (IN_FILE_NAME.c_str());
    if (FILE.is_open())
    {
        while( getline (FILE,EX_FILE_TEXT) )
        FILE.close();
    }
    else cout << "[Error - 001] Can't open "<< IN_FILE_NAME <<endl;
    return (EX_FILE_TEXT);
}

Because the output = (space)
closed account (4i67ko23)
Anyone can help me?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// read all the lines in a text file into one string with newlines stripped
std::string readfile_1( const std::string& in_file_name )
{
    std::ifstream file(in_file_name) ;

    std::string result ;
    std::string line ;
    while( std::getline( file, line ) ) result += line ;

    return result ;
}

// read contents of text file into a string
std::string readfile_2( const std::string& in_file_name )
{
    std::ifstream file(in_file_name) ;
    return std::string( std::istreambuf_iterator<char>(file),
                         std::istreambuf_iterator<char>() ) ;
}
Topic archived. No new replies allowed.