简体   繁体   中英

How do I find the last int of a string

I need a string taken as input from the keyboard for example A 2 DF 5 A, it always has 6 total characters, How do I find the last int, in this case 5 and store it in a variable? I cant find anything anywhere.

From the inte.net I found some code that half works

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;

struct not_digit {
    bool operator()(const char c) {
        return c != ' ' && !std::isdigit(c);
    }
};

int main() {

    int last;

    std::string Serial(" 1 S 4 W 2 A");
    not_digit not_a_digit;
    std::string::iterator end = std::remove_if(Serial.begin(), Serial.end(), not_a_digit);
    std::string all_numbers(Serial.begin(), end);
    std::stringstream ss(all_numbers);
    std::vector<int> numbers;

    for(int i = 0; ss >> i; ) {
        numbers.push_back(i);
        last = i;
    }

    cout << last << endl;

    return 0;
}

but I dont know how to take "Serial" from keyboard as doing so always results in the last number being 0 for some reason, so instead of 2 i get 0.

This would do:

  • Reverse the string.
  • Then find a digit in the string.
  • Notice the input string may not have digits.

[Demo]

#include <algorithm>  // find_if
#include <cctype>  // isdigit
#include <fmt/core.h>
#include <ranges>

int main() {
    std::string str(" 1 S 4 W 2 A");
    auto rev{ str | std::views::reverse };
    auto it{ std::ranges::find_if(rev, [](unsigned char c) { return std::isdigit(c); }) };
    if (it != std::cend(rev)) {
        fmt::print("Last int found: {}\n", *it);
    } else {
        fmt::print("No int found.\n");
    }
}

// Outputs:
//
//   Last int found: 2

Also:

  • Walking the string backwards.
  • And stopping once you find a digit.

[Demo]

#include <cctype>  // isdigit
#include <fmt/core.h>

int main() {
    std::string str(" 1 S 4 W 2 A");
    auto it{ std::crbegin(str) };
    for (; it != crend(str); ++it) {
        if (std::isdigit(*it)) {
            fmt::print("Last int found: {}\n", *it - '0');
            break;
        }
    }
    if (it == crend(str)) {
        fmt::print("No int found.\n");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM