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

时间:2020-01-04 08:49:30

标签: c++ type-conversion

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

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

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

1 个答案:

答案 0 :(得分:0)

我认为正则表达式将是最安全,最直接的解决方案。我不认为这是多余的,因为您只需创建一次正则表达式,但是可以多次匹配它。

#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";
        }
    }
}