Searching and printing from a text file

Title is ambiguous, but, basically, I have a text file with three columns - the first one is from T1 to T104 and means Try1, Try2..., second and third columns are the results in the particular try, separated by commas, (results from some game, let's say) given as integers. Each Try (T) is on a separate row. For example: T3 5, 3

What I need to do is be able to open the file and print the results for a given try (attempt). For example, if the user enters "T3" i need to print the results for T3 - "5" and "3" to say.

What approach do I take?

Here is what I have so far, but I can't quite get it working:
I know for sure that my condition in the if loop in the getCode function is not right - it now just prints everything.

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
43
44
45
 #include <iostream>
#include <string>
#include <map>
#include <fstream>
using namespace std; 

string getCode(string& line)
{
    string store;
    for (int i=0; i < line.size(); i++)
    {
        if(line[i]=='T' || line[i]>='0' && line[i]<='9')
        {
            store+=line[i];
        }

    }
    return store;
}

int main()
{
    ifstream in_file("input");
    string str;
    map<string, string> Tries;

    while(getline(in_file, str))
    {
        string Code=getCode(str);
        Tries[Code]=str.substr(Code.size()+1, str.size());
    }
    
    cout<<"Enter code: ";
    string Code;
    cin >> Code;
    
    string Result = Tries[Code];
    if(Result!="")
        cout<< Result << endl;
    else
        cout << "try not found"<<endl;
    
  return 0;
}
Last edited on
You could use a stringstream to parse the line into fields.
(In this example I used a stringstream as a substitute fro an input file - the behaviour should be the same as an ifstream).
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
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <map>

using namespace std;

int main()
{
    istringstream in_file(
        "T3 5, 3\n"
        "T7 8, 4\n"
        "T11 6, 7\n"
    );
    
    map<string, string> Tries;
    
    string str;
    while ( getline(in_file, str) )
    {    
        istringstream ss(str);
        string code, rest;
        ss >> code >> ws;
        getline(ss,rest);
        if (ss)
            Tries[code] = rest; 
    }
    
    string Result = Tries["T7"];
    if (Result != "")
        cout << Result << endl;
    else
        cout << "try not found" << endl;

}
Last edited on
Topic archived. No new replies allowed.