Tags

, , , , , , , , , ,

The Problem: I have the following file (say, “inp.txt”) that contains some data and I want to read the values of different types in a c++ code.

num_1 = 123
num_2 = 10.9e-2

I put the variable names in order to remind myself to assign the right values to the right variables.

Solution: One way to do this is to use an istringstream instance. Here’s a sample code:

//
// Parse input given as key = value (values may be of different type)
//
#include<iostream>
#include<fstream>
#include<string>
#include <sstream>
using namespace std;

int main(){

    // Input stream
    ifstream InpStream("inp.txt");

    // We want to get parsed num_1 and num_2
    int num_1;
    double num_2;

    // Define strings to hold the key and corresponding value
    string key, value;

    // Read the input file using getline ('=' is the delimiter)
    while ( getline(InpStream, key, '=') ) {

        // Print what key is read
        cout << "key read: " << key << endl;

        // Create an istringstream instance to parse the key
        // (string to sring conversion)
        istringstream ss_key(key);
        ss_key >> key;

        // Now read the value and print what is read (value is a string)
        getline(InpStream, value);
        cout << "value read: " << value << endl;

        // Create another istringstream instance to parse the value
        istringstream ss_value(value);

        if ( key == "num_1") {
            // string to integer conversion
            ss_value >> num_1;
            cout << "Parsed num_1: " << num_1 << endl;
        }
        else if (key == "num_2") {
            // string to double conversion
            ss_value >> num_2;
            cout << "Parsed num_2: " << num_2 << endl;
        }
        cout << endl;
    }
    return 0;
}

Here’s the output

key read: num_1
value read: 123
Parsed num_1: 123

key read: num_2
value read: 10.9e-2
Parsed num_2: 0.109

Reference: DaniWeb, Cplusplus.

Advertisements