2

Okay I read that if we have a string s =" 1 2 3"

we can do :

istringstream iss(s);  
int a;
int b;
int c;

iss >> a >> b >> c;

Lets say we have a text file with the following :

test1
100 ms

test2
200 ms

test3
300 ms

ifstream in ("test.txt")
string s;
while (getline(in, s))
{
       // I want to store the integers only to a b and c, How ?
}
Axalo
  • 2,953
  • 4
  • 25
  • 39
Tharwat Harakeh
  • 89
  • 1
  • 3
  • 11

2 Answers2

0

1) You can rely on succesful convertions to int:

int value;
std::string buffer;
while(std::getline(iss, buffer,' ')) 
{
    if(std::istringstream(buffer) >> value)
    {
        std::cout << value << std::endl;
    }
}

2) or just skip over unnecessary data:

int value;
std::string buffer;
while(iss >> buffer) 
{
    iss >> value >> buffer;
    std::cout << value << std::endl;
}
Alexey Andronov
  • 582
  • 6
  • 28
0

If you know the pattern of the details in the text file, you could parse through all the details, but only store the int values. For example:

ifstream in ("test.txt")
string s;
while (getline(in, s))
{
     getline(in,s); //read the line after 'test'.
     string temp;
     istringstream strm(s);
     s >> temp;
     int a = stoi(temp) // assuming you are using C++11. Else, atoi(temp.c_str())
     s >> temp;
     getline(in,s); // for the line with blank space
}

This above code is still somewhat of a inelegant hack. What you could do besides this is use random file operations in C++. They allow you to move your pointer for reading data from a file. Refer to this link for more information: http://www.learncpp.com/cpp-tutorial/137-random-file-io/

PS: I haven't run this code on my system, but I guess it should work. The second method works for sure as I have used it before.

therainmaker
  • 4,253
  • 1
  • 22
  • 41