2011-03-28 111 views
0

我要解决以下任务:MVS C++错误:串标超出范围

有被赋予一个文本文件“pesel.txt”,其中包含150所国家认同。每行包含一个国家标识,这是一个11位数字编号。前两位数字从左边开始确定年份,一个人出生在哪一年,后两位数字决定月份,下两个决定日期。

为了缩短:0-1 =年

数字 位2-3 =月 数字4-5 =天 位6-11 =确定别的东西,是什么并不重要

我需要阅读这个文件,检查有多少人在十二月出生。我想这以下列方式:

  • 读取每一行直至到达文件末尾
  • 在每一行我检查字符串中的第三个字符是否等于1,如果第四个字符等于2,如果是我增加变量,这是我出生在十二月的人反,否则在下一个循环中执行

这里是代码:

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/

+0

行是空的,或者您正在访问不存在的数据。 – DumbCoder 2011-03-28 10:58:18

回答

2

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; 
} 
1

之前,如果打印出来的线,看看它是否具有正确的价值,你也可以检查线路的长度访问之前:

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

如果您编写代码,并且您希望某个值是特定的某个值,那么可以使用断言(如果该值不符合预期并且您立即捕获该错误)。

#include <cassert> 
assert(line.size() == 10 && "line size is not equal to 10"); 
+0

你是对的检查线的长度是至关重要的。 我检查过.txt文件,每行都包含11位数字,但最后一行是空的,导致了这个问题。它现在有效,谢谢。 – koleS 2011-03-28 11:19:43

+0

@ user659389当你问一个问题时,如果你得到一个解决方案,不要忘了把答案放在正确的位置。 – hidayat 2011-03-28 12:23:44

0

嘛。很明显,由于断言消息状态在程序中使用的std :: string下标超出了下标2(来自行[2])或下标3(来自行[3])的范围。这意味着其中一行读取的内容少于4个字符,因此您没有第四个字符(行[3])。可能是如果文件尾随,文件中可能为空的最后一行。

由于陶菲克和Erik已经写在自己的岗位上,你至少可以做的是检查,如果线够长。