Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 读取要存储在变量中的行的一部分_C++_Variables_Fstream_Readline - Fatal编程技术网

C++ 读取要存储在变量中的行的一部分

C++ 读取要存储在变量中的行的一部分,c++,variables,fstream,readline,C++,Variables,Fstream,Readline,我试图从文件中获取字符串的其余部分,以将字符串存储在变量中。例如,第一行是“1234中国上海”,但变量查询只得到“上海”,而不是“中国上海”。权重得到1234。我猜这与城市和乡村之间的空间有关 while (!file.eof()) { string query; long weight; file >> weight >> query; Term inputTerm(query,weight); } 大概是这样的: long weigh

我试图从文件中获取字符串的其余部分,以将字符串存储在变量中。例如,第一行是“1234中国上海”,但变量查询只得到“上海”,而不是“中国上海”。权重得到1234。我猜这与城市和乡村之间的空间有关

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

我假设您使用的是标准的iostream类?如果您使用的是file.getLine(),我现在使用的是getLine(file,line)。仍然面临同样的问题。请发布代码,然后你的工作!我在哪里可以找到关于“char query[100]”含义的信息?任何涉及基础知识的书籍。它只是一个由100个字符组成的数组,用作将行读入的缓冲区。传递给getline函数的100是要读取的最大字符数,与缓冲区大小匹配,因此它不会溢出缓冲区。好的。谢谢我想当时我读的那本书不是很好。