C++ 从文本文件中检索某一行,只知道C+中的起始编号(但需要整行)+;
我有一个文本文件,我需要通过它来获得一个特定的行,我知道该行包含的前6个字符,但是当前代码不想停止将该行复制到另一个字符串,而是返回列表中的最后一个结果 以下是当前的代码实现:C++ 从文本文件中检索某一行,只知道C+中的起始编号(但需要整行)+;,c++,text,getline,C++,Text,Getline,我有一个文本文件,我需要通过它来获得一个特定的行,我知道该行包含的前6个字符,但是当前代码不想停止将该行复制到另一个字符串,而是返回列表中的最后一个结果 以下是当前的代码实现: std::string Type(int num) { ifstream reader("TypeID.txt", ios::in | ios::binary); //declaring the file input string str, replace = "failed"; int
std::string Type(int num)
{
ifstream reader("TypeID.txt", ios::in | ios::binary); //declaring the file input
string str, replace = "failed";
int search;
while (getline(reader, str));
{
search = str.find(num, 0);
if (search <= 0) // once find has found the string run this
{
replace = str; //copy current line of str to replace
reader.close();//after string is retrieved, close stream
}
}
reader.close();//after string is not retrieved, close stream
return replace;
}
以此类推,总共21760条线路的问题在于:
search = str.find(num, 0);
search
的类型是int
,但是find()
的返回类型是std::size\t
,因此类型不匹配。因此,您必须计算出当值超出范围时会发生什么情况(std::string::npos的值是多少?)
其次,返回的值是第一个匹配的位置(或std::string::npos)。因此,如果它被发现,我不希望结果小于零
if (search <= 0) // So this is not going to work.
if(search)您似乎将int num作为第一个参数传递给string::find()。您希望它做什么?您可能会看到find()试图找到一个数值为num%256的字符,这可能不是您想要的。您的代码有几个问题,首先解决matt的问题,然后看看您可能会继续使用封闭流读取器读取的事实。是否可以使用break语句?
if (search <= 0) // So this is not going to work.