c++ - MVS C++ 错误 : string subscript out of range

标签 c++ string

我想解决以下任务:

给定一个文本文件“pesel.txt”,其中包含 150 个国家身份。每行包含一个国家身份,这是一个 11 位数字。左边的前两位数字确定一个人出生的年份,接下来的两位数字确定月份,接下来的两位数字确定日期。

缩短:

数字 0-1 = 年份 数字 2-3 = 月份 数字 4-5 = 日 数字 6-11 = 确定其他内容,此处不重要

我需要读取文件,检查有多少人在 12 月出生。我试图通过以下方式做到这一点:

  • 读取每一行直到到达文件末尾
  • 在每一行我检查字符串中的第三个字符是否等于 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/

最佳答案

虽然 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;
}

关于c++ - MVS C++ 错误 : string subscript out of range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5457968/

相关文章:

c++ - 重新声明纯虚函数

c++ - 在我的新游戏中找不到内存泄漏?

c++ - Qt的QBuffer线程安全吗?

c++ - C/C++ 中的无限循环

linux - 在csh中提取字符串

java - swig从struct中的变量获取返回类型作为java中的字符串数组

c++ - 当保护保护太多

Java 在循环中迭代字符串数组并一次返回

python - 有没有办法覆盖 __format__ 方法

python - 在python中,你如何检查一个字符串是否同时包含大写和小写字母