How to extract number from a string in C++

3 Answers

0 votes
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>
#include <cctype>
#include <algorithm>
 
using std::cout;
using std::string;
using std::vector;
 
bool is_number(const string &s) {
    return !s.empty() && find_if(s.begin(),
        s.end(), [](char c) { return !isdigit(c); }) == s.end();
}
 
int main()
{
    string s = "abcd 97 efghi";
 
    std::istringstream iss(s);
    vector<string> tokens{ std::istream_iterator<string>{iss},
        std::istream_iterator<string>{} };
 
    int n;
    for (string s : tokens)
        if (is_number(s))
            n = stoi(s);
 
    cout << n;
}
 
 
 
 
/*
run:
 
97
 
*/

 



answered May 27, 2018 by avibootz
edited Aug 29, 2023 by avibootz
0 votes
#include <iostream>
#include <string>
#include <cctype>
 
using std::cout;
using std::string;
 
int get_number(const string s)
{
    int n = 0;
    for (int i = 0; i < s.length(); i++) {
        if (isdigit(s[i]))
            n = n * 10 + (s[i] - '0');
    }
    return n;
}
 
int main()
{
    string s = "abcd 97 efghi";
 
    int n = get_number(s);
 
    cout << n;
}



 
/*
run:
 
97
 
*/

 



answered May 27, 2018 by avibootz
edited Aug 29, 2023 by avibootz
0 votes
#include <iostream>
#include <string>
#include <cctype>
 
using std::cout;
using std::string;
 
int get_number(const string s)
{
    int n = 0;
    for (int i = 0; i < s.length(); i++) {
        if (isdigit(s[i]))
            n = n * 10 + (s[i] - '0');
    }
    return n;
}
 
int main()
{
    string s = "abcd987efghi";
 
    int n = get_number(s);
 
    cout << n;
}
 
 
 
 
/*
run:
 
987
 
*/

 



answered May 27, 2018 by avibootz
edited Aug 29, 2023 by avibootz

Related questions

1 answer 128 views
1 answer 113 views
2 answers 159 views
1 answer 115 views
1 answer 160 views
1 answer 138 views
...