If I had a string "Num123" how would I get "123" and have it as an int? Thanks
Three answers:
anonymous
2013-08-13 20:28:06 UTC
To extract a number from a string we can use methods within the string stream class (along with the string class of course). So make sure to include that library. For example if we were to convert and integer number in a string into an ingerger we would use: int myInt = atoi(myString.c_str()); c_str() means to convert the string, while atoi() means to interpret the item as an Integer in base-10.
#include
#include
#include
int main()
{
std::string myString = "123";
int myInt = atoi(myString.c_str());
std::cout << myInt;
}
To make sure there are no errors first have a function manipulate and return a new string that takes out anything that is not an digit. This can be accomplished with regular expressions, so it would be a good idea to include .
Equinox
2013-08-13 20:19:25 UTC
First, you would need to get rid of Num. There are many ways to get a number from string type, but not that accept malformed numbers.
There are ways with regex, but they are complicated. An easier way is to write a linear parsing function that pulls all numbers from the string (if the character at that under is within the 0-9 range), and delimit it however you want. For example, "123a456" could be 123456 or 123 and 456.
Once you have your number parsing how you want it (build strings from those characters), then you can use atoi with a cstring or string stream with a std::string to get the number. Google their usage.
cja
2013-08-15 07:18:51 UTC
A stringstream object will be most useful to you for this. Here's an example:
#include
#include
#include
#include
#include
using namespace std;
bool isDigit(char c) { return isdigit(c); }
bool isNotDigit(char c) { return isdigit(c) == false; }
int main(int argc, char *argv[]) {
string s;
string::iterator i;
stringstream ss;
int n;
while (true) {
cout << "> ";
getline(cin, s);
for (i = s.begin(); i != s.end(); ) {
if ((i = find_if(i, s.end(), isDigit)) != s.end()) {
stringstream(string(i, s.end())) >> n;
cout << n << endl;
i = find_if(i, s.end(), isNotDigit);
}
}
}
return 0;
}
#if 0
Sample run:
> Num123
123
> a = 123, b = 456
123
456
> n99xyz
99
> hello, world
>
#endif
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.