Hello there, I recently need to use c++ to do a project, and I occur some problems, hoping can get some advices from here, many thanks!

My project allow a user to input a number and i need to retrieve the data from a text file.
My text file's data is like below:
tom 100
bunny 150
goofy 160
jerry 170
spiderman 350
looneytune 350
powerpuffgirls 400

the format of the file is "name TAB/2TAB number", and the distance of all the number from the begin of the line is two TAB, it is not spaces.


when a user input 2, i need to retrieve"bunny 150" from text file and separate them into two part:
word: bunny
digit: 150

now i manage to retrieve the whole line depending on the user's input, but i don't know how to separate that line i get, can anyone here me? thanks~

following is my code so far:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

  int main()
{   
    int x;
    string input;
    do{    
    cout << "Please enter a number between 1-20:";
    getline(cin, input);  
    x = atoi(input.c_str());   
                                     
    if (x >= 1 && x <= 20) 
    {
           cout<< "Output: " << x << endl;
           string line; //this will contain the data read from the file
           ifstream myfile ("guess.txt"); //opening the file.
           if (myfile.is_open()) //if the file is open
           {
           string a;
               for(int i = 0; i < x ; i++)
               {
                   getline (myfile,line); //get one line from the file
                   a = line;
               } 
               myfile.close(); //closing the file
               cout << a << endl;
           }
    }
    else
        cout<< "Out of range, only allow 1-20." << endl;
    }while(1==1);
}

You can use strtok.

Amit

instead of getline() you could use the >> extract operator

string name;
int number;
int line_count = 0;
while( myfile >> name >> number && line_count < x)
{
    ++line_count
}

Thanks amt_muk and Ancient Dragon, I solve my problem by using Ancient Dragon's suggestion, thanks alot~

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.