dimanche 26 novembre 2017

Out_of_range and cannot open for writing error in Microsoft Visual Studio

I was having some issues with this code that I wrote. It takes this file of text:

MS    Bach,   Johann    S.
FMCurie,     Marie A.
FS Parker, Alice   M.
FD       Meir,Golda T.
MDRobeson, Paul 
MM         Ashe,    Arthur 
FM  Tubman, Harriet          A.
MSBraille,Louis 

and uses the information to reformat the names based off of their gender and the marital status. My programming teacher added spaces in the input file to test our ability to use strings correctly in code. I was doing fine coding, until I ran the final program, and it gave me an "out_of_range" error. I tried it again, and this time it said that the error "LNK1168 cannot open C:\Users\Pujan Ajmera\source\repose\machineproblem6\Debug\machineproblem6.exe for writing". I went through the code several times, and I could not see a problem in it that would allow for this or the previous error. How can I fix this?

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

enum maritalstatus { MARRIED, DIVORCED, SINGLE, NONE };
using namespace std;
string gender(string g, maritalstatus ms)
{
    if (g == "M")
    {
        return "Mr. ";
    }
    else if (g == "F")
    {
        if (ms == SINGLE || ms == DIVORCED)
        {
            return "Ms. ";
        }
        else if (ms == MARRIED)
        {
            return "Mrs. ";
        }
        else if (ms == NONE)
        {
            return "ERROR. ";
        }
    }
}

maritalstatus marital_status(string MS)
{
    if (MS == "M")
    {
        return MARRIED;
    }
    else if (MS == "S")
    {
        return SINGLE;
    }
    else if (MS == "D")
    {
        return DIVORCED;
    }
    else
    {
        return NONE;
    }
}

int main()
{
    ifstream infile;
    infile.open("mp6Names.txt");
    ofstream outfile;
    outfile.open("mp6output.txt");
    string str;
    maritalstatus ms;
    bool noMI = 0;
    while (!infile.eof())
    {
        getline(infile, str);
        string MS = str.substr(1, 1);
        maritalstatus ms = marital_status(MS);
        string g = str.substr(0, 1);
        string prefix = gender(g, ms);
        string MI;
        if (str.find(".", 0) != string::npos)
        {
            string MI = str.substr(str.find(".") - 1, 2);
        }
        else
        {
            string MI = "";
            noMI = 1;

        }
        string firstName = str.substr(str.find(",", 0) + 1);
        string truncatedfirstName = firstName.substr(str.find(!" ", 0), str.find(" ", str.find(!" ", 0)) - str.find(!" ", 0));
        string lastName = str.substr(2, str.find(",", 0) - 2);

        if (noMI == 1)
        {
            outfile << prefix << truncatedfirstName << " " << lastName << "\n";
        }
        else
        {
            outfile << prefix << truncatedfirstName << " " << MI << " " << lastName << "\n";
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire