Thread: compare strings:

  1. #1
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499

    compare strings:

    I am trying to figure out how to go about comparing two strings of numbers. I have two files that both contain numbers 1-50, one file has multiple repeating numbers while the other one just has 1-50.

    I want to compare the files and count how many of each number a occurred and make a chart with * next to the number. First I figured I would use the strings like an array and compare them using nested loops. Then I noticed I have single and double digit numbers. The numbers in the files are printed as:

    1 44 5 34 4
    2 22 7 55 4
    ...... etc

    Compared too:
    1
    2
    3
    4
    5
    ......
    50


    I thought about using string stream and converting the string to int but wouldn't it just be a huge number when set to the int variable? Then I thought about a array initialized with 1-50 and compared to the file but I still have the issue with single and double digit numbers. Advice?

    My question is how can I just read one number at a time, either double or single digit?

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    I suggest you think about using int instead of string. You could then use the extraction operator to extract these numbers into your int. You may want to study up on Basic file input and output.


    Jim

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Extract all of the ints from the first file into a container (such as a vector<int>). Then you can use a standard algorithm like std::count() and supply it integers (one at a time) from the second file.

    You're really claiming you don't know how to read a single int from a file? What do you think "some_stream >> some_int" does???
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    I was being a boob, it took me 5 min to write once I woke up. My head was a little foggy. Sorry for posting that...

  5. #5
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Here is the code I wrote this morning and asked about last night when I was a little out of it. Now did I go about this the hard way? I sometimes find myself doing that. Now please excuse it all being in main, I understand my design should have included a class or at least some functions. My while statement on line 39 is what I am really asking about.
    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <iomanip>
    #include <algorithm>
    
    struct compare
    {
        bool operator() (int x, int y){ return (x<y);};
    
    }MyCompare;
    
    int main(int argc, const char * argv[])
    {
    
        std::vector<int>num;
        std::vector<int>commonNum;
        int lottoNum;
    
        std::ifstream infile("textfile.txt"); //opening lotto numbers
        
        while (infile>>lottoNum) { num.push_back(lottoNum); } //pushing numbers from file into vector
        
        for (auto it = num.begin(); it!=num.end(); ++it)
        {
            for (int compare = 1; compare<=49; ++compare) {
                if (compare==*it) {
                    commonNum.push_back(*it); //pushing common numbers to common Num vector
                }
            }
        }
        std::sort(commonNum.begin(), commonNum.end(), MyCompare);//sorting the numbers
        
        for (int i=0; i<commonNum.size(); i++)
        {
            int count = 1;
            size_t limit = commonNum.size();
            
            while (i<limit && commonNum[i]==commonNum[i+1]) //comparing the current number with the next
            {
                count++;
                i++;
            }
            std::cout<<commonNum[i]<<"\t"<<count<<"\n"; //current number and how many time it occurred
        }
        
        infile.close();
        
        return 0;
    }

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You're not changing commonNum inside that loop (lines 34-45), so maybe computing limit once outside the loop would be a good idea. (On the other hand, you're not using it outside the loop, so keeping the scope down is probably a good idea; and the compiler may well optimize it out anyway.)

    Writing your own comparator may well be good practice, but that comparator that you've written already exists (std::less<int>, if memory serves; in fact, I think that's the default for std::sort anyway).

    I don't think I understand the purpose of the loop on lines 24-31; are we just trying to make sure all the numbers are between 1 and 49? If so, why not just restrict when we add to the num vector in the first place? (Also you keep spinning through the loop even when the number is added.)

  7. #7
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    
    struct compare
    {
        bool operator() (int x, int y){ return (x<y);};
    
    }MyCompare;
    
    int main(int argc, const char * argv[])
    {
    
        std::vector<int>num;
        std::vector<int>commonNum;
        int lottoNum;
    
        std::ifstream infile("textfile.txt"); //opening lotto numbers
        
        while (infile>>lottoNum) { num.push_back(lottoNum); } //pushing numbers from file into vector
        
        std::sort(num.begin(), num.end(), MyCompare);//sorting the numbers
        
        size_t limit = num.size();
        for (int i=0; i<num.size(); i++)
        {
            int count = 1;
            
            while (i<limit && num[i]==num[i+1]) //comparing the current number with the next
            {
                count++;
                i++;
            }
            std::cout<<num[i]<<"\t"<<count<<"\n"; //current number and how many time it occurred
        }
        
        infile.close();
        
        return 0;
    }
    Yea I fixed that. I was completely on a different thought and when I had a better idea I just went in a different direction and didn't clean up after myself. You can tell in the libraries too.

  8. #8
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    Look at the following snippet:
    Code:
        size_t limit = num.size();
        for (int i=0; i<num.size(); i++)
        {
            int count = 1;
             
            while (i<limit && num[i]==num[i+1]) //comparing the current number with the next
            {
                count++;
                i++;
    First you have a variable named limit that is the same as the for loop condition, why don't you use that instead of recomputing the size()?

    Next incrementing your for loop counter (i) inside the for loop is a bad practice. You really shouldn't be incrementing this variable more than once. The way these loops are structured your for() loop probably only executes once.

    You also need to check and insure your file opened correctly.

    Also you'll be accessing your array out of bounds on the last iteration of your loop because of that i+1.

    Jim

  9. #9
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Thank you... I have fixed the out of bounds error, I didn't even see that.
    Code:
      size_t limit = num.size()-1;
        
        for (int i=0; i<limit; i++)
        {
            int count = 1;
            
            while (i<limit && num[i]==num[i+1]) //comparing the current number with the next
            {
                count++;
                i++;
            }
            std::cout<<num[i]<<"\t"<<count<<"\n"; //current number and how many time it occurred
        }
    I checked for the file too. I suppose since it was a fun program and I manually put the txt file into the folder I didn't think of it. It is a bad habit to not think of it I would assume so thank you again.

    Now I have been studying different data structures and the Big O etc. Lets say I have 1000 number, would a vector be the best course of action? I know that after so many variables a vector will copy itself in memory and continue but sometimes using more then necessary. If I used a linked list here after so many nodes it would be cumbersome on the computer. Granted the computers have fast today but I just wanted to know in case one day I have to make a decision.

    I know an array would be best as far as the Big O is concerned but I will not know how many variables I will be inputing to the array prior to reading the file.

  10. #10
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    What about this problem?
    Next incrementing your for loop counter (i) inside the for loop is a bad practice. You really shouldn't be incrementing this variable more than once. The way these loops are structured your for() loop probably only executes once.
    Jim

  11. #11
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by jimblumberg View Post
    What about this problem?


    Jim
    That part is correct (counting repeated values inside the vector, after they have been sorted to be contiguous). Not the only way you could do it, but it is a reasonable way.

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Tip: Using the .at() function(s) can help you catch out-of-bounds problems easier. Unless you are working on an embedded platform, it usually works pretty well.
    Informative: You don't need to close files. They close automatically. In fact, this is one of the ground principles of C++ called RAII that objects should do cleanup automatically once they are destroyed, so you don't have to close/free stuff manually.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to compare strings in c++
    By Sanscorp1999 in forum C++ Programming
    Replies: 3
    Last Post: 08-12-2012, 04:03 PM
  2. compare two strings
    By cable in forum C Programming
    Replies: 3
    Last Post: 02-07-2012, 09:12 AM
  3. compare strings
    By jamal in forum C Programming
    Replies: 6
    Last Post: 11-27-2011, 08:09 PM
  4. Trying to compare to strings...
    By imortal in forum C++ Programming
    Replies: 9
    Last Post: 05-16-2003, 12:27 PM
  5. how do i compare strings
    By bart in forum C++ Programming
    Replies: 17
    Last Post: 08-30-2001, 09:17 PM