将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量

阿隆索

所以我的程序将“A1、A2、B2、H8”等中的输入作为坐标。例如,当用户输入“A1”时,它们会被分配到一个名为“spaceInput”的字符串。但是为了 for 循环(在下面的代码块之外)迭代并找到匹配的数字 '1',它必须变成一个 int 然后分配给 'numberInput'。

我使用了“stoi()”,但问题是它需要受到保护,否则它会崩溃,例如,当有人输入“AA”之类的东西时。代码工作正常,但有没有更好的方法将字符从字符串转换为整数?

void TakeInput() {

    string spaceInput;
    int numberInput;
    char letterInput;

    while (true) {
        cout << "Enter your space input: " << endl;
        cin >> spaceInput;
        cout << spaceInput << endl;
        cin.get();
        letterInput = toupper(spaceInput[0]);// Converts letter input to uppercase

        try { 
            int numberInput = stoi(spaceInput.substr(1)); 
               if (spaceInput.size() == 2 && numberInput < ROWS && numberInput > 0) {
                SearchSpace(spaceInput, letterInput, numberInput);
                cout << "Your input was: " << letterInput << numberInput << endl;
               }

               else {

                cout<< "Invalid input: " << endl;

            }
        }   catch (exception const &e) {
            cerr << e.what() << endl;
        }
    }
}
卢卡斯·格拉斯

我认为正则表达式将是最安全和直接的解决方案。我不认为这是矫枉过正,因为您创建了一次正则表达式,但要多次匹配它。

#include <string>
#include <iostream>
#include <regex>

int main(void)
{
    std::string input;
    std::regex regex("[A-Z|a-z][0-9]");

    while (true) {
        std::cin >> input;

        if (std::regex_match(input, regex)) {
              char letter = input[0];
              int number = atoi(&input[1]);

             std::cout << "Input letter: " << input[0] << std::endl;
              std::cout << "Input number: " << number << std::endl;;
        } else {
              std::cout << "Formatting error\n";
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章