C++ 如果INI文件中的某行在C+中的长度大于n,则跳过读取该行+;
如果INI文件中的行超过1000个字符,我想跳过读取。这是我正在使用的代码:C++ 如果INI文件中的某行在C+中的长度大于n,则跳过读取该行+;,c++,mfc,ini,getline,C++,Mfc,Ini,Getline,如果INI文件中的行超过1000个字符,我想跳过读取。这是我正在使用的代码: #define MAX_LINE 1000 char buf[MAX_LINE]; CString strTemp; str.Empty(); for(;;) { is.getline(buf,MAX_LINE); strTemp=buf; if(strTemp.IsEmpty()) break; str+=strTemp; if(str.Find("^")>-1)
#define MAX_LINE 1000
char buf[MAX_LINE];
CString strTemp;
str.Empty();
for(;;)
{
is.getline(buf,MAX_LINE);
strTemp=buf;
if(strTemp.IsEmpty()) break;
str+=strTemp;
if(str.Find("^")>-1)
{
str=str.Left( str.Find("^") );
do
{
is.get(buf,2);
} while(is.gcount()>0);
is.getline(buf,2);
}
else if(strTemp.GetLength()!=MAX_LINE-1) break;
}
//is.getline(buf,MAX_LINE);
return is;
我面临的问题是,如果字符数超过1000,if似乎陷入无限循环(无法读取下一行)。如何使getline跳过该行并读取下一行???如何检查
getline
的返回值,如果失败则中断
..或者如果是
是一个istream,您可以检查是否存在eof()条件来中断
#define MAX_LINE 1000
char buf[MAX_LINE];
CString strTemp;
str.Empty();
while(is.eof() == false)
{
is.getline(buf,MAX_LINE);
strTemp=buf;
if(strTemp.IsEmpty()) break;
str+=strTemp;
if(str.Find("^")>-1)
{
str=str.Left( str.Find("^") );
do
{
is.get(buf,2);
} while((is.gcount()>0) && (is.eof() == false));
stillReading = is.getline(buf,2);
}
else if(strTemp.GetLength()!=MAX_LINE-1)
{
break;
}
}
return is;
对于完全不同的东西:
std::string strTemp;
str.Empty();
while(std::getline(is, strTemp)) {
if(strTemp.empty()) break;
str+=strTemp.c_str(); //don't need .c_str() if str is also a std::string
int pos = str.Find("^"); //extracted this for speed
if(pos>-1){
str=str.Left(pos);
//Did not translate this part since it was buggy
} else
//not sure of the intent here either
//it would stop reading if the line was less than 1000 characters.
}
return is;
这使用字符串以便于使用,并且对行没有最大限制。它也使用了<代码> STD:GETLION/CODE >动态/魔术的一切,但我没有翻译中间的一部分,因为它对我来说似乎很笨拙,我无法解释意图。
中间的部分一次只读取两个字符,直到它到达文件的末尾,然后所有的东西都会做奇怪的事情,因为你没有检查返回值。因为它是完全错误的,所以我没有解释它。
你能发布一个完整的样本吗?什么是“是”?你为什么要跳过这一行?为什么不使用string
或CString
?
std::string strTemp;
str.Empty();
while(std::getline(is, strTemp)) {
if(strTemp.empty()) break;
str+=strTemp.c_str(); //don't need .c_str() if str is also a std::string
int pos = str.Find("^"); //extracted this for speed
if(pos>-1){
str=str.Left(pos);
//Did not translate this part since it was buggy
} else
//not sure of the intent here either
//it would stop reading if the line was less than 1000 characters.
}
return is;