Jakob Busk Sørensen
Jakob Busk Sørensen

Reputation: 6081

Reading integers from a file returns incorrect output (ifstream)

In my attempt to make an automatic Sudoku solver in C++, the first step I need is to read the 9x9 grid from a file. Currently I just try to simply read the data, and display it as output, however the output is not correct. My code is as following:

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    // Initialize string for the lines to be read in
    string line;

    // Create the object to read the file "data.txt"
    ifstream sudokuData("data.txt");

    // Check if file opened properly
    if (!sudokuData.good()) {
    cout << "Couldn't open the file.\n";
    }

    // Read only if file exists
    if ( sudokuData.is_open() ) {

        cout << "Starting to read from file... \n";

        // Read as long as there are lines in the file
        while ( getline(sudokuData,line) ) {
            cout << line << '<\n';
        }

        // Close file once done reading
        sudokuData.close();

    } else {
        // If file cannot be read, inform the user
        cout << "Unable to open file";
    }
        return 0;
}

Which from all I can find, is correct. The data file contains the numbers from 1 to 9 in each row, separated by a space. An example line would be:

1 2 3 4 5 6 7 8 9

But when I run the code, I get the following output:

Starting to read from file 
153709 1 2 3 4 5 6 7 815370
RUN SUCCESSFUL (total time: 38ms)

What the heck am I doing wrong?

I'm using NetBeans 8.0 as IDE, if that is of any use...

Upvotes: 2

Views: 1503

Answers (1)

Homero C. de Almeida
Homero C. de Almeida

Reputation: 199

There is a typo in your code. At line 27 you define a multi-byte char constant with '<\n'. Remove the < sign and it should work fine.

Upvotes: 6

Related Questions