我想解决以下问题:
给出了一个文本文件"pesel.txt",其中包含150个国家身份。每一行包含一个国家身份,这是一个11位数字号码.从左开始的两位数决定一个人出生的年份,下两位数字决定月份,下两位数字决定日期。
缩短:
数字0-1 =年份数字2-3 =月份数字4-5 =日数字6-11 =确定其他东西,这里不重要的是什么
我需要看一下文件,看看12月有多少人出生了。我正以下列方式尝试这样做:
。
以下是代码:
int _tmain(int argc, _TCHAR* argv[])
{
ifstream file( "C:\\Kuba\\Studia & Nauka\\MATURA XDDD
\\INFA\\1\\Dane_PR\\pesel.txt" );
string line;
int bornInDecember=0;
if( !file.is_open() ){
cout << "Cannot read the file." << endl ;
}else{
while( file.good() ){
getline( file, line );
if( line[2] == '1' && line[3] == '2' ){
bornInDecember++ ; // 0-1 year, 2-3 month, 4-5 day
}
}
cout << "Amount of people born in december : "<< bornInDecember<< endl;
file.close();
}
system("pause");
return 0;
}问题是,我得到了以下错误,我不知道为什么。
http://img10.imageshack.us/i/mvserr.png/
发布于 2011-03-28 10:59:25
while file.good()错了-- getline仍然会失败。读取文件的最后一行,处理它,file.good()仍然是正确的,然后尝试再读一行,getline失败。
在访问line[n]之前,您还需要检查行是否足够长--否则您将得到所得到的错误。
int _tmain(int argc, _TCHAR* argv[])
{
ifstream file( "C:\\Kuba\\Studia & Nauka\\MATURA XDDD\\INFA\\1\\Dane_PR\\pesel.txt" );
string line;
int bornInDecember=0;
if( !file.is_open() ){
cout << "Cannot read the file." << endl ;
} else {
while (getline(file, line)) { // While we did read a line
if (line.size() >= 4) { // And the line is long enough
if( line[2] == '1' && line[3] == '2' ){ // We check the condition
bornInDecember++ ; // 0-1 year, 2-3 month, 4-5 day
}
}
}
cout << "Amount of people born in december : "<< bornInDecember<< endl;
file.close();
}
system("pause");
return 0;
}发布于 2011-03-28 11:01:01
在if之前,打印出该行并查看它是否具有正确的值,您还可以在访问它之前检查行的长度:
std::getline( file, line );
std::cout << line << std::endl;
if( line.size() >= 4 && line[2] == '1' && line[3] == '2' )
...您还应该使用while(std::getline(file, line))而不是while(file.good())。
如果您编写代码并期望某个值是特定的,则如果该值不像预期的那样并立即捕获错误,则可以使用assert。
#include <cassert>
assert(line.size() == 10 && "line size is not equal to 10");发布于 2011-03-28 11:16:48
井。显然,当断言消息声明为std::string下标时,程序中使用的字符串下标超出了范围,即下标2(来自line2)或下标3(来自line3)。这意味着读取的一行小于4个字符,因此没有第四个字符(line3)这样的内容。这可能是文件中可能为空的最后一行,如果您在文件中拖尾的话。
正如hidayat和Erik已经在他们的帖子中所写的,你至少可以检查一下这条线是否足够长。
https://stackoverflow.com/questions/5457968
复制相似问题