Search code examples
c++variablesfstreamreadline

Reading part of a line to store in a variable


I'm trying to get the rest of a string from a file to store the string in a variable. For example, the first line is "1234 Shanghai, China" but the variable query only gets "Shanghai," instead of "Shanghai, China." Weight gets 1234. I'm guessing it has something to do with the space between the city and country.

while (!file.eof())
{
    string query;
    long weight;
    file >> weight >> query;
    Term inputTerm(query,weight);
}

Solution

  • Something like this:

    long weight;
    char query[100];
    while (file >> weight)
    {
        file.getline(query, 100);
        Term inputTerm(std::string(query), weight);
    }