Blood Brother
Blood Brother

Reputation: 103

Extracting different data types variables from a string

I'm trying to get my hands dirty with File IO here. I'm able to do basic stuff but kinda ran out of ideas here. I want to read input from a text file. Each line of the text file follows this format: <int> <char> <string literal> <float>, if it doesn't it is to be ignored.

And for each line, we need to store the variables in say four data types:

int i;
char c;
std::string  s;
float f;

And print them. For the next line, they are overwritten and printed again.

Here's my attempt:

int main() {
    int i;
    char c;
    std::string  s, x;
    float f;
    ifstream in;
    in.open("Input.txt");
    if(in) {
        std::getline(in,x);
        // How do I extract i, c, s and f components from x now?
        cout << "\nInteger:" << i << ", Character: " << c << ", String: " 
             << s << ", Float: " << f << endl; 
    }
    return 0;
}

PS: Despite efficiency bottlenecks, please use only elementary concepts to solve this issue, not advanced stuff.

Upvotes: 1

Views: 983

Answers (1)

vsoftco
vsoftco

Reputation: 56547

You can simply do:

while(in >> i >> c >> s >> f)
{
    cout << "\nInteger:" << i << ", Character: " << c << ", String: " 
         << s << ", Float: " << f << endl; 
}

If your values are comma-separated, you can use a std::stringstream/std::getline combination to parse the tokens (std::getline allows specifying a separator), like so:

std::stringstream ss; // from <sstream>
int field = 0; 
while (std::getline(in, ss, ','))
{
    switch (field)
    {
    case 0:
        ss >> i; 
        break;
    case 1:
        ss >> c;
        break;
    case 2: 
        ss >> s;
        break;
    case 3:
        ss >> f;
        break;
    }
    if(++field == 4)
        field = 0;
}

Or, you can read the whole line, remove the commas (std::remove_if), send the transformed line into a stringstream, then do ss >> i >> c >> s >> f.

Upvotes: 3

Related Questions