c++ substr (2)

Posted on 2007-10-21
Last Modified: 2012-06-27
take a look at my question here:

Problem is that i accept answer, but when i checked code it wont work correctly. I need just one word as output, but it gives output:
and so on...
this time, i will share points who will help me ;)
last time, i gave all points to one guy, because i didn't knew how to give to few people.
Question by:moonskyland
    LVL 53

    Expert Comment

    The problem is that you use 0 as starting point for the substr call every time ... You have to modify the starting point every time you call the substr function.

    As I said in the other thread : you shouldn't have just taken his code, but should have tried to find the solution yourself ... you probably wouldn't have had this problem then :)

    Try to understand what the code does. Take a look at this reference page for substr - it will help you :


    Also, did you get rid of the deprecated <iostream.h> include as I said in your other question ?
    LVL 10

    Accepted Solution

    Your loop conditional needs to look something like this:

    while((n = s.find(" ", i)) != string::npos)

    Think about what types and initial values n and i might have.

    Actually, a 'do' loop would probably work better.
    LVL 7

    Assisted Solution

    by:lucky_james should have told me that the code is not working. i would be glad to help you. I saw your comment in the previous thread and this thread. :)

    flaw in the logic : you need to recognise that you have got one word already rather than restarting from start of the string.

    Anyway try this code:
         int i;
        string s;  
        cout << "Enter Sentence:\n";
        getline(cin, s);
          string s2(" ");
        cout << "You entered:" << s << "\n";
                for(i = 0; i<=s.length();i++)
                      if (s[i]== ' ' )
                            s2 =  s.substr(0, i);
                            cout << s2 << "\n" ;
          return 0;

    Hope it helps.

    Infinity : hats off to you....guys like you think for the welfare of the community. I am posting code becoz now he can see the difference between the previous code and this one.

    LVL 7

    Expert Comment

    this time i have tried it hands on
    so, more probability for you not saying 'some guy took away points and his code didnt work' :)

    take care...
    LVL 39

    Assisted Solution

    >>>>                       s.erase(0,i+1);

    erasing the extracted substring may solve the initial problem but is nevertheless inefficient and not needed here.

    >>>> for(i = 0; i<=s.length();i++)
    don't make i<=s.length() cause s[i] was not well-defined for i >= s.length(). It may work nevertheless cause std::string adds a zero character at end of string but actually that isn't a must and should be avoided. You also should see that  (s[i]== ' ' ) would not be true if s[i] is the zero character, so the last substring would not be recognized with loop lucky_james posted.

    Better use something like that:

        s += ' ';   // we add a space character at end to get a final delimiter
        int npos = 0;
        int lpos = 0;
        while ((npos = (int)s.find_first_of(" \n\t\r", lpos)) != string::npos)
               lpos = npos + 1;

    With that we find any 'whitespace' character like space, linefeed, carriagecontrol and tab. Furthermore we also find multi occurences of these, e. g. two spaces, what means that for the ... we could make a check like that:

               if (npos > lpos)  

    what prevents us from extracting an empty substring if two whitespace character were in sequence. The final replacement for the ... is now to get the substring between the two whitespace characters. We *know* that it begins at lpos cause lpos was npos+1 where (old) npos was a whitespace and it ends at (new) npos-1 cause we found the next whitespace char there.

             cout << "substring: " << s.substr(lpos, npos - lpos) << endl;

    Regards, Alex

    LVL 53

    Assisted Solution

    >> Infinity : hats off to you....guys like you think for the welfare of the community. I am posting code becoz now he can see the difference between the previous code and this one.

    Instead of posting code, explain what should be changed, and why. That way, the asker will have to think about it, and come up with his own way of implementing the suggested changes. It also makes sure that the asker understands the changes, which is what this is all about.

    If you just post code, then the asker will usually just test if it works, and leave it at that without having learned a lot more than copy-pasting. Although that's a good thing to learn, it's not gonna help him/her in later assignments, and the problem he/she has with the current assignment will manifest itself again later.
    Or in other words : you provided a short-term solution to finish his assignment, but you didn't provide a long-term solution to teach something that the asker can use in all his other assignments, and in his professional life.
    LVL 7

    Expert Comment

    Well, each of the change i made, i explained each change in the code.....furthermore, the code is the like limitless sky, you can always find a room to improve it....Alex is already on to it.  :)
    Still, I honor ur valuable comments.....

    Featured Post

    Top 6 Sources for Identifying Threat Actor TTPs

    Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

    Join & Write a Comment

    What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
    Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
    The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
    The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

    731 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now