0

I am the newbie of C++.

I want to write a program that can read the file such lik below:

p   6   9
n   3
b   1   6.0
b   1   4.0
b   2   2.0

In such file, I want to read the line with first char b.
I try to use getline() and to judge whether the first char is b.
However, I face the problem is I can easily save the first int, but the second double number I can't save it. I know the reason is I save it in char, so the dobule number are seperated(such like 6.0 become '6' '.' '0').
Thus, does it have other way to save the line with integer and double?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){

    char b[100];
    string word;
    int a,d;
    double c;
    ifstream infile("test.txt");
    while(infile){
        infile.getline(b,100);
        if(b[0] == 'b'){
            //where I don't know how to save the data
        }
    }
}

I'm sorry for my rusty English, but really need your help.

1
  • You might want to read about std::istringstream. With it you can use the normal input operator >>. Commented Feb 19, 2014 at 17:43

1 Answer 1

2

Just put the whole string into a std::istringstream and use >> to get its data out:

int int_value;      // second data will be saved here, e.g. 1
float float_value;  // third data will be saved here, e.g. 6.0

char char_dummy;    // dummy char to hold the first char, e.g. 'b'
istringstream iss(b);
iss >> char_dummy >> int_value >> float_value;
Sign up to request clarification or add additional context in comments.

1 Comment

Since you control the format of the data, solutions like istringstream are your friend. It is very clean and less error-prone than older C-style solutions like fscanf, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.