读取一行的一部分以存储在变量中

Reading part of a line to store in a variable

我正在尝试从文件中获取字符串的其余部分以将字符串存储在变量中。例如,第一行是“1234 Shanghai, China”,但变量查询只得到 "Shanghai," 而不是 "Shanghai, China." 权重得到 1234。我猜它与 space城乡之间

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

像这样:

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

您可以使用它来阅读一行的其余部分:

std::string ReadLine(std::ifstream& file){
    char buf[1024]; //Unfortunately this means you can only have a max of 1024 char string
    file.getline(&(buf[0]),1024,'\n');
    return std::string(buf);
}

这样使用:

file >> weight;
query = ReadLine(file);