运行后C ++控制台崩溃

时间:2016-07-15 13:52:14

标签: c++

伙计们,我有一个问题。 运行程序后,控制台崩溃了。 terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::replace: __pos (which is 4294967295) > this->size() (which is 9)

我的意思是,你会看到。在程序中有一个选项"添加人",当我添加一个,它一切都没关系。但是当我进入程序添加第二个人时它崩溃了。请帮助!

程序的源代码是:

#include <iostream>
#include <windows.h>
#include <string>
#include <algorithm>
#include <fstream>
using namespace std;

int main(){

system("chcp 1251 > nul");
system("title PeopleData");

string firstName;
string midName;
string lastName;
string fullName;
string line;
long ID = 27560000;
int age;
char gender;

cout << "1.Add person" << endl;
cout << "2.Read file" << endl;
cout << "3.Exit" << endl << endl;
cout << "Please, enter your choice: ";
int choice;
cin >> choice;

if(choice == 1)
{
    system("cls");

    ofstream myfile("Data.txt", ios::app);

    ifstream file("Data.txt");
    string IDLine;
    int numberOfLines = 0;
    if (myfile.is_open())
    {
        while (getline (file, line) )
        {
            numberOfLines ++;
        }
        file.close();
        ifstream file("Data.txt");
        int y = 0;
        line = "";
        while(getline(file, line))
        {
            IDLine = line;
            if(y == numberOfLines - 5)
            {
                goto NextStep;
            }
            y++;
        }
    }
    else
    {
        cout << "Unable to open file";
    }

    NextStep:
    string LastID = IDLine;
    if(LastID != "")
    {
        LastID.replace(LastID.find("ID: "), string("ID: ").length(), "");
        ID = atoi(LastID.c_str()) + 1;
    }
    else
    {
        ID = 27560000;
    }
    cout << "First Name: ";
    cin >> firstName;
    cout << endl << endl;

    cout << "Middle Name: ";
    cin >> midName;
    cout << endl << endl;

    cout << "Last Name: ";
    cin >> lastName;
    cout << endl << endl;

    cout << "Age: ";
    cin >> age;
    cout << endl << endl;

    cout << "Gender (m / f): ";
    cin >> gender;

    fullName = firstName +  " " + midName + " " + lastName;

    myfile << "First Name: " << firstName << "\n";
    myfile << "Middle Name: " << midName << "\n";
    myfile << "Last Name: " << lastName << "\n";
    myfile << "Full Name: " << fullName << "\n";
    myfile << "Age: " << age << "\n";
    myfile << "Gender: " << gender << "\n";
    myfile << "ID: " << ID << "\n";
    myfile << "\n---------------\n\n";
    myfile.close();
    file.close();
    return 0;
}

if(choice == 2)
{
    system("cls");
    ifstream myfile ("Data.txt");
    if (myfile.is_open())
    {
        while ( getline (myfile,line) )
        {
            cout << line << '\n';
        }
        myfile.close();
    }
    else
    {
        setcolor(12);
        cout << "Unable to open file";
    }
}
if(choice == 3)
{
    return 0;
}

system("pause > nul");
return 0;

} `

0 个答案:

没有答案