The Minimal Example that reproduces the issue is as follows:
#include <iostream>
#include <string>
#include <list>
#include <iterator>
#include <vector>
#include <cctype>
class Tokenizer{
public:
void TokenizeLine(const std::string& CurrLine)
{
std::list<std::string> sList;
std::size_t bPos = 0;
char c = 0;
int nTokens = 0;
while(bPos < CurrLine.size())
{
c = CurrLine[bPos];
if (isspace(c))
{
bPos++;
continue;
}
else
sList.push_back(this->ReadSimpleToken(bPos, CurrLine));
}
this->_Tokens.clear();
this->_Tokens.reserve(nTokens);
std::copy(sList.begin(), sList.end(), std::back_inserter(_Tokens));
}
std::string ReadSimpleToken(std::size_t& start, const std::string& line)
{
std::size_t startpos = start;
std::size_t currpos = start;
while(currpos < line.size() && !isspace(line[currpos]))
currpos++;
return line.substr(startpos, currpos - startpos);
}
int GetNumberOfTokens()
{
return (int) _Tokens.size();
}
private:
std::vector<std::string> _Tokens;
};
int main() {
// Write C++ code here
std::string test{"staticstructural nsteps 1 nmodules 1"};
Tokenizer t;
t.TokenizeLine(test);
std::cout << "Output: " << t.GetNumberOfTokens() << std::endl;
return 0;
}
The above code seems to compile, but doesn't give the desired output.
However, when I replace the method ReadSimpleToken() with the below implementation:
std::string Tokenizer::ReadSimpleToken(std::size_t& start, const std::string& line)
{
std::size_t startpos = start;
// std::size_t currpos = start;
while(start < line.size() && !isspace(line[start]))
start++;
return line.substr(startpos, start - startpos);
}
It works perfectly fine.
Can anyone explain to me what is wrong with the first implementation?
In the first implementation, I am updating currpos, until it reaches either the end of the string or the character at currpos is a space char. This should be same if I am assigning currpos to be start or if I am doing the same for start itself. The only difference between both implementations is that the first one uses currpos and second one does the same but with only start.
I tried this with g++ and whatever compiler progamiz uses. The link is here:
start.start, and does not work if you do not (because you modify a copy instead). Even without looking at the role ofstart, I do not find a change in behavior unusual. Why do you think the behavior should be the same? (Explain your understanding of how your code should work.)