Czy istnieje jakaś możliwość znalezienia liczby w stringu jeśli na przykład mamy w stringu litery i białe znaki
na przykład: "bd 3 dbbsda" i jak odnaleźć 3
0
1
Podejrzewam, że istnieje ładniejszy sposób:
int getInt(const string& source)
{
stringstream buf(source);
string s;
while (buf >> s)
{
int value;
try
{
value = stoi(s);
}
catch (const invalid_argument& e)
{
continue;
}
return value;
}
throw invalid_argument("no number in the given string");
}
0
#include <iostream>
#include <locale>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <cstring>
using namespace std;
string extract_ints(ctype_base::mask category, const string &str, ctype<char> const& facet){
char const *begin = &str.front(), *end = &str.back();
auto res = facet.scan_is(category, begin, end);
begin = &res[0];
end = &res[strlen(res)];
return string(begin, end);
}
string extract_ints(const string &str){
return extract_ints(ctype_base::digit, str, use_facet<ctype<char>>(locale("")));
}
int main(){
string str = "Jennifer and each of her 2 other friends had 3 kittens.";
int friends_num, kittens_num;
stringstream ss(extract_ints(str));
ss >> friends_num >> kittens_num;
cout << friends_num << " " << kittens_num;
return 0;
}
0
Po co się męczyć?
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
string a;
getline(cin,a);
for(int i=0;i<a.size();i++)
{
if(isdigit(a[i])) cout<<"Liczba w stringu to: "<<a[i]<<endl;
}
}
Możesz także utworzyć tablice typu int
z cyframi i porównywać każdy element do elementu stringa
0
@aksjio LICZBA != CYFRA
0
Tak wiem o tym ale kolega szuka gotowca, ja tylko pokazałem w jaki sposób może szukać cyfr w stringu. Można mój program szybko zmodyfikować by sprawdzał czy następny znak też jest cyfrą.