克服“字符串下标超出范围”读取文件时的断言 [英] Overcome "string subscript out of range" assertion when reading a file
问题描述
您好,
我需要从文件sample.txt中读取数据并将特定行存储到另一个文件中。 sample.txt有大约6000行,以'$'开头的行必须存储在另一个文件中。
但是,当文件指针(用于读取操作)达到eof时,它会触发断言失败消息 - 字符串下标超出范围。
克服这个断言的任何想法?
提前致谢!
我的尝试:
代码:
ifstream fi;
ofstream of;
string str;
fi.open(sample.txt,ios_base :: binary);
of.open(output.txt,ios_base :: binary);
while(!fi.eof())
{
getline(fi,str);
if(str [ 0] =='$')
{
<< str;
of<<\ n; < br $>
}
}
fi.close();
of.close();
PS:sample.txt和output.txt已经创建。
Hello,
I'm required to read data from a file "sample.txt" and store specific lines into another file. sample.txt has around 6000 lines and lines that start with '$' have to be stored in another file.
However, when the file pointer (for read operation) reaches eof it triggers an assertion failure message - string subscript out of range.
Any ideas of overcoming this assertion?
Thanks in advance !
What I have tried:
code:
ifstream fi;
ofstream of;
string str;
fi.open( "sample.txt", ios_base::binary );
of.open( "output.txt", ios_base::binary );
while ( ! fi.eof() )
{
getline( fi, str );
if( str[0] == '$' )
{
of<<str;
of<<"\n";
}
}
fi.close();
of.close();
P.S : sample.txt and output.txt have already been created.
推荐答案
'必须存储在另一个文件中。
但是,当文件指针(用于读取操作)达到eof时,它会触发断言失败消息 - 字符串下标超出范围。
克服这种说法的任何想法?
提前致谢!
我的尝试:
代码:
ifstream fi;
ofstream of;
string str;
fi.open(sample.txt,ios_base :: binary);
of.open(output.txt,ios_base :: binary);
while(!fi.eof())
{
getline(fi,str);
if(str [ 0] =='
' have to be stored in another file.
However, when the file pointer (for read operation) reaches eof it triggers an assertion failure message - string subscript out of range.
Any ideas of overcoming this assertion?
Thanks in advance !
What I have tried:
code:
ifstream fi;
ofstream of;
string str;
fi.open( "sample.txt", ios_base::binary );
of.open( "output.txt", ios_base::binary );
while ( ! fi.eof() )
{
getline( fi, str );
if( str[0] == '
')
{
of<< str;
of< ;<\ n;
}
}
fi.close();
of .close();
PS:已经创建了sample.txt和output.txt。
' )
{
of<<str;
of<<"\n";
}
}
fi.close();
of.close();
P.S : sample.txt and output.txt have already been created.
if( str[0] == '
这篇关于克服“字符串下标超出范围”读取文件时的断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!