Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading/parsing text file input c++

Tags:

c++

input

A little background: I am working on a sliding block puzzle for a school project and this is our first using C++ instead of Java. This is the first time I have had to implement something that reads data from a file.

I have a simple question regarding reading input from a text file. I understand how to read the file line by line and hold each line in a string, I want to know if I can parse the string into different data types as the file is read.

Currently I am reading each line and storing them as strings in a vector for parsing later, and I know there must be a much simpler way to implement this

The first line holds 2 integers which will indicate the length and width of the grid, the following lines will have 4 integers and a char for use as arguments when creating the blocks.

My question is this, if I read the file character by character instead, is there a function I can use that will detect if the character is an integer or a char (and ignore the spaces) so I can store them immediately and create the block objects as the file is read? How would i deal with integers >10 in this case?

EDIT: Just noting I am using fstream to read the files, I am unfamiliar with other input methods

A sample input:

4  4
3  1  2  1  b
1  1  1  1  a 
like image 453
Gadesxion Avatar asked Dec 27 '22 04:12

Gadesxion


1 Answers

To detect whether a piece of string can be parsed as an integer, you just have to parse it and see if you succeed. The best function for that would probably be std::strtoul(), since it can be made to tell you how many characters it consumed, so that you can continue parsing after that. (See the man page for details.)

However, if you already know the format of your file, you can use iostream formatted extraction. This is quite straightforward:

#include <fstream>


std::ifstream infile("thefile.txt");

int n1, n2, x1, x2, x3, x4;
char c;

if (!(infile >> n1 >> n2)) { /* error, could not read first line! Abort. */ }

while (infile >> x1 >> x2 >> x3 >> x4 >> c)
{
    // successfully extracted one line, data is in x1, ..., x4, c.
}

Another alternative is to read every line into a string (using std::getline), then creating a stringstream from that line, and parsing the stringstream with >>. This has the added benefit that you can discover and skip bad lines and recover, while in the direct formatted extraction I presented above, you cannot recover from any error.

like image 157
Kerrek SB Avatar answered Jan 06 '23 09:01

Kerrek SB