Thread: substr in a for loop isn't working correctly

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    308

    substr in a for loop isn't working correctly

    I have substr working in a for loop, but its missing a matching letter;

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
         string msg = "apple";
         string msg2 = "padlock";
         string string_block;
    
         for (int i = 0; i+1<msg.length(); ++i){
            string_block = msg.substr((msg[i] == msg2[i]) == 0) ;   // second argument of substr is length, not end.
            cout << "String Block: " << string_block[i] << endl;
         }
    
        return 0;
    }
    The output;

    String Block: p
    String Block: p
    String Block: l
    String Block: l

    Process returned 0 (0x0) execution time : 0.000 s
    Press any key to continue.

    __________________

    As you see, the letter 'a' is missing.


    This one works;

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
         string msg = "aapple";
         string msg2 = "padlock";
         string string_block;
    
         for (int i = 0; i+1<msg.length(); ++i){
            string_block = msg.substr((msg[i] == msg2[i]) == 0) ;   // second argument of substr is length, not end.
            cout << "String Block: " << string_block[i] << endl;
         }
    
        return 0;
    }
    The results;

    String Block: a
    String Block: a
    String Block: p
    String Block: l
    String Block: e

    Process returned 0 (0x0) execution time : 0.000 s
    Press any key to continue.

    ________

    But now there is an 'e'.

  2. #2
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    This works, but it returns too many results;

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
         string msg = "aapple";
         string msg2 = "padlock";
         string string_block;
        for (int a = 0; a+1<msg.length(); ++a){
            for (int b = 0; b+1<msg2.length(); ++b){
                if((msg[a] == msg2[b]) == 0) ;   // second argument of substr is length, not end.
                cout << "String Block: " << msg[a] << endl;
            }
        }
    
        return 0;
    }
    The results;


    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: l
    String Block: l
    String Block: l
    String Block: l
    String Block: l
    String Block: l

    Process returned 0 (0x0) execution time : 0.000 s
    Press any key to continue.

  3. #3
    Internet Superhero
    Join Date
    Sep 2006
    Location
    Denmark
    Posts
    964
    I'm not sure what you think string::substr does, but it seems you got it wrong:

    string::substr - C++ Reference

    Also, this:

    Code:
    if((msg[a] == msg2[b]) == 0) ;
    Doesn't do anything, since you have a semi-colon at the end.
    How I need a drink, alcoholic in nature, after the heavy lectures involving quantum mechanics.

  4. #4
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    I missed that typo, here is the new code;

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
         string msg = "aapple";
         string msg2 = "padlock";
         string string_block;
        for (int a = 0; a+1<msg.length(); ++a){
            for (int b = 0; b+1<msg2.length(); ++b){
                if((msg[a] == msg2[b]) == 0){    // second argument of substr is length, not end.
                cout << "String Block: " << msg[a] << endl;
                }
            }
        }
    
        return 0;
    }
    And the new results;

    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: a
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: p
    String Block: l
    String Block: l
    String Block: l
    String Block: l
    String Block: l

    Process returned 0 (0x0) execution time : 0.016 s
    Press any key to continue.

    ____________

    I'm busy playing online right now, but I will look at that link after, thanks.

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    This:
    Code:
    if ((msg[a] == msg2[b]) == 0)
    is the same as this:
    Code:
    if (msg[a] != msg2[b])
    The later of course being more readable.

    So you're printing a letter from the first string every time it doesn't match a letter from the second string, except that you've also coded it to skip the last character from both strings.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  6. #6
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    I was trying to use substr to find matching chars between two strings, but I found another way, so I don't need substr.

    Here is the function;

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
         string msg = "aapple";
         string msg2 = "padlock";
         string string_block;
        for (int a = 0; a<msg2.length(); a++){
            for (int b = 0; b<msg.length(); b++){
                if(msg[a] == msg2[b]){    // second argument of substr is length, not end.
                cout << "String Block: " << msg[a] << endl;
                }
                else{
                continue;
                }
            }
        }
    
        return 0;
    }
    Here is the results;

    String Block: a
    String Block: a
    String Block: p
    String Block: p
    String Block: l

    Process returned 0 (0x0) execution time : 0.016 s
    Press any key to continue.

    ________________

    So problem solved.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    If you had taken a little more time to examine the string functions other than substr, then you may have discovered that your code can be simplified, e.g.,
    Code:
    #include <iostream>
    #include <string>
     
    using namespace std;
     
    int main()
    {
        string msg = "aapple";
        string msg2 = "padlock";
        for (string::size_type i = 0; i < msg.length(); ++i) {
            if (msg2.find(msg[i]) != string::npos) {
                cout << "String Block: " << msg[i] << endl;
            }
        }
     
        return 0;
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    Thanks for the code laserlight. I'm probably going to be redoing my program later on to make it have better code and be easier to read, and if I do I'll change the code I gave as my answer for the code you just gave me.

  9. #9
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    Quote Originally Posted by jeremy duncan View Post
    I'm probably going to be redoing my program later on to make it have better code and be easier to read.
    Don't think in that way.
    Resolve the 'problem' first, with a pencil , preferably.
    After you are sure what you're going to code, the program will naturally look more structured... not a horrible mess.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    By the way, your code actually contains a latent bug: your array indices a and b are based on the lengths of msg2 and msg respectively, but then you access msg[a] and msg2[b] instead of msg2[a] and msg[b].
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    laserlight, Thanks a lot for catching that bug. I fixed it.

  12. #12
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    I don't know what to do. Here is my code;

    Code:
    void findMatch(){
        string temp1;
        string temp2;
        vector<string> text_file1;
    
        std::ifstream hfin1("holdSentence.txt", fstream::app), fin2("holdDatabase.txt", fstream::app);
        if (!hfin1 || !fin2) { std::cerr<<"file error\n"; std::exit(1); }
    
        getline( hfin1, temp1 );
    
        while( getline( fin2, temp2 ) ){
    
            for (string::size_type a = 0; a < temp2.length(); ++a) {
                if(temp2[a] == '4' ){
                    for (string::size_type b = 0; b < temp1.length(); ++b) {
                        if(temp1[b] == '1' ){
    
                            cout << endl << temp2 << " " << temp1 << endl;
                        }
                    }
                }
            }
    
            text_file1.push_back( temp2 );
        }
    
        hfin1.close();
        fin2.close();
    }
    And here is my program output;

    Code:
    Enter your sentence, end it with a period: apple.
    
    Input sentence to program, from input.txt;
     appplle
     xxxyy 4  appplle 1  // This is from the function
    
     yyyzz 4  appplle 1  // This is from the function
    
     zzzaa 4  appplle 1  // This is from the function
    
    
    Press any key to continue . . .
    See this result "zzzaa 4 appplle 1", I want the function to display "zzzaa 4" only, because the two strings "zzzaa " and " appplle " share a char. I have tried many different things for a few days now and I think I have to use substr, but for the life of me I don't know how to use substr in my function to get the result I want.
    Last edited by jeremy duncan; 05-29-2012 at 04:17 PM.

  13. #13
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    What I'm trying to do, if you look at my previous post, is find the string from temp1 that has the char '1' and the string from temp2 that has the char '4', this compare the two strings and find a matching char, then display the entire string from temp 2 that has the matching char. I have been trying to do this for a while now and I think it has me beat, so any suggestions would be very nice. I'm sorry if I was not the coder you thought I should be, but I am still here and still trying, which should count for something.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by jeremy duncan
    What I'm trying to do, if you look at my previous post, is find the string from temp1 that has the char '1' and the string from temp2 that has the char '4', this compare the two strings and find a matching char, then display the entire string from temp 2 that has the matching char.
    There appears to be some confusion with terminology here. temp1 and temp2 are variables of type std::string, so we say that they are strings. Thus "find the string from temp1" does not make sense.

    What I suspect you mean is "find the word in temp1", where you define "word" as "contiguous sequence of non-whitespace characters" or something like that. However, I don't understand what you mean by "has the char '1'" when you also say "compare the two strings and find a matching char".

    I suggest that you define "word" then rephrase what you want to do in terms of "words". Clearly state example input and expected output, and how you arrived at the expected output.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    Is there any reason you're not using std::string.find to find the strings with '1' and '4'? Then you could even use std::string.find_first_of() to possibly see if any characters from string 1 are contained in string 2.

    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Loop not working Correctly
    By patneel in forum C Programming
    Replies: 4
    Last Post: 03-15-2012, 07:25 AM
  2. Max/min function not working correctly
    By En-Motion in forum C++ Programming
    Replies: 6
    Last Post: 03-19-2009, 12:28 AM
  3. Pointers are not working correctly
    By adrian_fpd in forum C Programming
    Replies: 8
    Last Post: 11-17-2008, 07:55 PM
  4. function not working correctly
    By mackieinva in forum C Programming
    Replies: 0
    Last Post: 09-29-2007, 08:22 PM
  5. File I/O not working correctly
    By gL_nEwB in forum C++ Programming
    Replies: 4
    Last Post: 05-27-2006, 10:29 PM