Re: Searching a String, and counting occurrences of an Integer within the String
On Mar 9, 7:15 am, kingbarsa <barry.kingw...@gmail.com> wrote:
while (start != std::string::npos)
{
start = stop;
stop = str.find( ' ',start );
....
This loop does not seem to advance, in that the first value for stop
(in the case of my test string) is 3, which is the first location of a
space.
The next iteration (as i understand it) the find should start looking
from "start" onwards thereby find the next occurance of a space,
however for all iterations on, both start and stop have the value 3,
and the loop continues eternally.
I then tried
start = stop + 1;
which works in that the find seems to find the next space rather than
refind the same space.
However it becomes a problem when it gets to the end, in that it seems
that when stop = std::string::npos and start = stop + 1, then start
resorts back to zero, instead of also being = npos.
And so it starts reading from the beginning of the string all over.
Any advice, most appreciated
Rather than worry about individual spaces, let the string operator >> do
the heavy lifting for you.
size_t parse2(char const *buf)
{
bool isFldAng = strstr(buf,"FLD ANG") != NULL;
std::istringstream instring(buf);
std::string token;
std::vector<int> num;
// by default the following line will skip white space
// and token will be complete.
while( instring >> token)
{
bool digit = isdigit(token[0]) != 0;
if( digit)
num.push_back(atoi(token.c_str()));
}
return num.size(); // counted number of ints
}
int main()
{
char const buff[] = "DWT 5 10 15 20 25 30 40 50 60 70
80 90 FLD ANG\n";
parse2(buff);
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]