Reputation: 692
I read a line from a text file, where in the end of the line there are numbers (format: "some text.001"), and I would like to get the number after the 0 or 0s. So if it's 001, then 1, if it's 010, then it's 10. What I got now:
fgets(strLine, 100, m_FileStream);
// Here I need to cut the numbers into myNum
int num = atoi(&myNum);
I tried with strrchr to get the position of the ".", but don't know what's next. Maybe I need strtok, but i don't know how to use it.
Upvotes: 1
Views: 265
Reputation: 10507
The function strtol()
(or a variant) is your friend for number conversion - prefer it to atoi()
as you've got more control over conversion and error detection. For a C++ approach, you could use STL:
string s = "some text.001";
size_t p = s.find_last_of('.');
cout << (( p != string::npos ) ? strtol( s.substr(p+1).c_str(), NULL, 0 ) : -1) << endl;
Output:
1
Upvotes: 0
Reputation: 2322
I think this should work:
fgets(..);
int iPos = strLine.find_last_of('0');
string strNum = strLine.substr(iPos, strLine.length()-iPos);
int num = ...
http://www.cplusplus.com/reference/string/string/find_last_of/
Haven't tested it though.
Upvotes: 0
Reputation: 122458
This is a C solution, not C++, but should work:
const char *filename = "some text.001";
char *p = strrchr(filename, '.');
if (p != NULL)
{
int num = atoi(p+1);
printf("%d\n", num);
}
else
{
// No extension
}
Upvotes: 0
Reputation: 122011
Once you have the position of the .
you can advance by one char
and use atoi()
:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char buf[20] = "some text.010";
char* period_ptr = strrchr(buf, '.');
if (period_ptr)
{
printf("%d\n", atoi(++period_ptr));
}
return 0;
}
Upvotes: 4