Isolating numbers from a string.

Hello, for my assignment, we have to read in a file which contains a series of numbers. The file will look like this:

i1 i2 i3 i4 i5 d6 i7 d8 i999

The sequence will be random. Every integer will have only "i" or "d" in front of it.

We have to write a program that will output something like this:

1
2
3
4
5
6
7
I = 1
I = 2
I = 3
I = 4
I = 5 
D = 6
…


I have written a program that works, but it only works if there is a space between the character and the number.

Such as:

i 1 i 2 i 3...

My question is how can I make my program work without having to put the spaces in between the character and the numbers?

Here is my code so far:

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
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void RunList(string a);

int main(){
        string name;

        // Ask for filename and send it to function.
        cout << "Filename >> ";
        cin >> name;
        RunList(name);

	system("pause");
        return 0;
}

void RunList(string a){
        // Open file for reading
        ifstream data;
        data.open(a.c_str());
        string stuff;

        // Read file till EOF
        while(data >> stuff){
                int in;

                data >> in;
                if(stuff == "i"){
                        cout << "I = " << in << endl;;
		}
                // If "d" is encountered
                else if(stuff == "d"){
                        cout << "D = " << in << endl;
                }

		data.clear();
        }

}


Thanks.
Last edited on
Get rid of the spaces. Extract the first element of the string. That's your prefix. Then the rest of the string needs to be converted to a number. Stringstreams are useful for this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Read file till EOF
while(data >> stuff){                           
    char prefix = stuff[0];                     
    string number(stuff.begin()+1, stuff.end());
    stringstream iss(number);                   
    int in;                                     
    iss >> in;                                  
                                           
    if(prefix == 'i'){                     
        cout << "I = " << in << endl;;     
    }                                      
    // If "d" is encountered               
    else if(prefix == 'd'){                
        cout << "D = " << in << endl;      
    }                                      
                                           
    data.clear();                          
}                                          

stuff = "i1"
prefix = 'i'
number = "1"  Now we need to convert it to a number
stick it in a stream

in = 1
Last edited on
Thank you, that did it!
Topic archived. No new replies allowed.