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);
}

Dani AI

Generated

Quick note tying the replies together and adding a robust way to split the line once it has been read:

suggested a C-style tokeniser and recommended formatted extraction; 's approach fixed the immediate problem for . For a slightly more robust parser (tolerant of variable numbers of tabs, extra whitespace, or names that may contain spaces), split at the last tab and trim the pieces; fall back to locating the first digit if tabs are missing.

#include <string>
#include <utility>
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <stdexcept>

static inline std::string trim(const std::string &s) {
    size_t left = s.find_first_not_of(" \t\r\n");
    if (left == std::string::npos) return "";
    size_t right = s.find_last_not_of(" \t\r\n");
    return s.substr(left, right - left + 1);
}

std::pair<std::string,int> split_name_number(const std::string &line) {
    size_t pos = line.find_last_of('\t');
    std::string name, numstr;
    if (pos != std::string::npos) {
        name = line.substr(0, pos);
        numstr = line.substr(pos + 1);
    } else {
        pos = line.find_first_of("0123456789");
        if (pos == std::string::npos) throw std::runtime_error("no number found");
        name = line.substr(0, pos);
        numstr = line.substr(pos);
    }
    name = trim(name);
    numstr = trim(numstr);
    char *endptr = 0;
    long val = std::strtol(numstr.c_str(), &endptr, 10);
    if (endptr == numstr.c_str() || *endptr != '\0') throw std::runtime_error("invalid number");
    return std::make_pair(name, static_cast<int>(val));
}

Notes: splitting by the last tab handles multiple tabs reliably. The digit-fallback is useful when the file might not use tabs consistently, but it can mis-split if names include digits; in that case prefer a regex that anchors the numeric token at the end (or require a strict separator). Use error checks around conversion (shown) so malformed lines do not silently produce wrong values. Operator>> is simpler and fastest when names are single tokens; strtok is a fine C-style option but less safe in C++ codebases.

Recommended Answers

All 3 Replies

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.