Snorlax
Snorlax

Reputation: 4735

C++: Why does my code stop running after the first for loop?

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. */

    string list[] = {"fiorello", "nonuterine", "asquint", "commodore", "semiprogressive",
                     "aviculturist", "brayley", "tendentious", "hungriness", "overbulkily",
                     "subfumigation", "praline", "fiorello", "presurvey", "unjealous",
                     "brayley", "unimpassionate", "welshman", "dcor", "traducianist"};

    int size = sizeof(list);
    for (int i = 0; i < size; i++) {
        cout << list[i] << endl; 
        // THIS IS WHERE I REALIZE NOTHING ELSE PRINTS AFTER THIS POINT.
    }
    cout << endl;

    int z = sizeof(list) / sizeof(list[0]);
    sort(list, list + z);
    for (int y = 0; y < z; y++) {
        cout << list[y] << endl;
    }

    return 0;
}

I don't have a strong background in C++, coming from HTML, CSS etc. so trying to figure this out.

What I'm trying to accomplish is to print out the array, then print out in alphabetical order, then find duplicates and remove and print out again. And lastly, find length of each word in array and print that out.

Upvotes: 0

Views: 107

Answers (1)

M.M
M.M

Reputation: 141544

As mentioned in comments, you are using sizeof incorrectly the first time. A good solution would be to not use it at all, instead use standard library algorithms which will find the size by template deduction:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    string list[]={"fiorello","nonuterine","asquint","commodore","semiprogressive","aviculturist","brayley","tendentious","hungriness","overbulkily","subfumigation","praline","fiorello","presurvey","unjealous","brayley","unimpassionate","welshman","dcor","traducianist"};

    // Operate on each item in list - don't need to mention count explicitly
    for ( auto&& s : list )
        cout << s << '\n'; 
    cout << endl;

    // Same as sort(list, list+z)
    sort( begin(list), end(list) );

    for ( auto&& s : list )
        cout << s << '\n'; 
    cout << endl;
}

Your comments suggest you plan to remove duplicates but you still want to use a C-style array. So presumably you'll be using a variable for the list count; you can get this by using:

size_t count = distance( begin(list), end(list) );

rather than using the sizeof thing. As well as being less error-prone, this will keep working even if you later change the code to use a container instead of a C-style array.

Upvotes: 2

Related Questions