Extract Numbers only from read File

I have a text file called "testCase.txt" that looks something like this:

TestCase1=1,0
TestCase2=5,8

I am currently able to read the entire file as a text but how do I extract the numbers 1 , 0 and 5 , 8 and push them into an array?

Code below is reading the file as a text

1
2
3
4
5
6
7
8
9
10
11
12
13
   int main()
    {
    
    fstream inputFile("testCase.txt", fstream::in);
    
    	string inputText;
    
    	while (getline(inputFile, inputText))
    	{
    		cout << inputText << endl;
    
    	}
    }
Last edited on
Read each line as a string. Find the = character. Put the rest of the string into a stringstream and read, e.g. 1,0 into int, char, int (or double, char, double).
You could use getline to read up to the =, then read an integer, a character (the comma), and an integer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
    for (string x; getline(cin, x, '='); )
    {
        int a, b;
        char ch;
        if (cin >> a >> ch >> b)
            cout << a << " : " << b << '\n';
    }
}

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;


vector<int> getNumbers( istream &str )
{
   vector<int> result;
   string line;
   char comma;
   int a, b;
   while ( getline( str, line, '=' ) && str >> a >> comma >> b >> ws ) 
   {
      result.push_back( a );
      result.push_back( b );
   }
   return result;
}


int main()
{
   stringstream in( "TestCase1=1,0\n"
                    "TestCase2=5,8\n" );
   vector<int> V = getNumbers( in );
   for ( int e : V ) cout << e << ' ';
}
Topic archived. No new replies allowed.