Reading in whole lines from file instead of word by word

I am able to read from the file I want just fine but the issue is it is read in word by word. So it comes out as:
John
Smith,
5,
10,
...

When in the text file it is written as:
John Smith, 5, 10, ...

Is there a way to read in line by line instead of word by word? Thank you! Code is below.

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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    
    cout << "Project One: Arrays and Files" << endl << endl;
    
    // Opening File
    ifstream fin;
    fin.open("CPSC121data.txt");
    
    // If file not found/fail to open
    if(fin.fail()) cout << "Open File Error!" << endl;
    
    // Displaying file contents
    string input;
    while(!fin.eof())
    {
        fin >> input;
        cout << input << endl;
        
    }
    
    // Once all contents are read/ Outro.
    cout << "End of file reached. Goodbye!" << endl << endl;
    
    
    return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    // open the file for input
    std::ifstream fin( "CPSC121data.txt" ) ;

    if( !fin.is_open() )
    {
        std::cout << "failed to open file for input\n" ;
        return 1 ;
    }

    std::string line ;
    // http://www.cplusplus.com/reference/string/string/getline/
    while( std::getline( fin, line ) ) // for each line read from the file
    {
        // print the line
        std::cout << line << '\n' ;
    }
}


Or:

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
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    // if the file is successfully opened for input
    if( std::ifstream fin{ "CPSC121data.txt" } ) // note: initialiser is within braces
    {
        std::string line ;
        // http://www.cplusplus.com/reference/string/string/getline/
        while( std::getline( fin, line ) ) // for each line read from the file
        {
            // print the line
            std::cout << line << '\n' ;
        }
    }

    else // attempt to open the file failed
    {
        std::cout << "failed to open file for input\n" ;
        return 1 ;
    }

}
Last edited on
Thank you!
Topic archived. No new replies allowed.