Home > database >  How do I take an input and make split it up into different integers?
How do I take an input and make split it up into different integers?

Time:06-09

So I think the title is a bit confusing, so I'll explain that again here: I would like to have someone input the string "11223344", and have the program set the values of integers to these numbers like so: int a = 11, int b = 22, int c = 33, int d = 44. Note: This will be used to input save codes for a game I am creating.

int PlayerSaveName;
int PLRlvl // level
int PLRmhp // max health
int PLRmap // max armor
int PLRdmg // attack damage
void SelectSave()
{   //----------
    Data_GamePhase = 2;
    WindowTitle();
    system("cls");
    //----------
    std::cout << "Enter your save code.\n";
    std::cout << "Code: ";
    std::cin >> PlayerSaveName;

// PlayerSaveNameFirstSection = PLRlvl;
// PlayerSaveNameSecondSection = PLRmhp;
// PlayerSaveNameThirdSection = PLRmap;
// PlayerSaveNameFourthSection = PLRdmg;
}

CodePudding user response:

You can use string::substr() and std::stoi(), eg:

std::string PlayerSaveName;
int PLRlvl; // level
int PLRmhp; // max health
int PLRmap; // max armor
int PLRdmg; // attack damage

void SelectSave()
{
    Data_GamePhase = 2;
    WindowTitle();
    system("cls");

    std::cout << "Enter your save code.\n";
    std::cout << "Code: ";
    std::cin >> PlayerSaveName;

    PLRlvl = std::stoi(PlayerSaveName.substr(0,2));
    PLRmhp = std::stoi(PlayerSaveName.substr(2,2));
    PLRmap = std::stoi(PlayerSaveName.substr(4,2));
    PLRdmg = std::stoi(PlayerSaveName.substr(6,2));

    PlayerSaveNameFirstSection = PLRlvl;
    PlayerSaveNameSecondSection = PLRmhp;
    PlayerSaveNameThirdSection = PLRmap;
    PlayerSaveNameFourthSection = PLRdmg;
}

CodePudding user response:

For generality, let's define a constant which holds the count of digits in each number:

constexpr int sectionSize = 2;

Now, we can read PlayerSaveName as std::string and split it into std::vector<int> of sections as follows, assuming that PlayerSaveName has multiple of sectionSize characters:

std::string PlayerSaveName;
// std::cout << ...
std::cin >> PlayerSaveName;
std::vector<int> sections;
for (size_t i = 0; i < PlayerSaveName.size(); i  = sectionSize)
{
    int currentNumber = 0;
    for (size_t j = i; j < i   sectionSize;   j)
    {
        const int currentDigit = PlayerSaveName[j] - '0';
        currentNumber = currentNumber * 10   currentDigit;
    }
    sections.push_back(currentNumber);
}

If we want to make sure that PlayerSaveName has proper number of characters, we can, for example, after reading it ask the user to enter the string again if needed, until PlayerSaveName is divisible:

//...
// std::cout << ...
std::cin >> PlayerSaveName;
while (PlayerSaveName.size() % sectionSize != 0)
{
    std::cout << "Save code is not divisible into " << sectionSize << "-digit numbers, enter again please: ";
    std::cin >> PlayerSaveName;
}
//...
  •  Tags:  
  • c
  • Related