Thread: two dimensional array problem

  1. #1
    Registered User
    Join Date
    Oct 2013
    Posts
    44

    two dimensional array problem

    Im sure this is an easy question to answer but i can seem to find it. Supposed to ask how many names to enter and then enter the names, first name only and store into a two dimensional array. cant have more than 20 names and each name cant be more than 15 characters long. for some reason when i put in how many names i want it set the array that size. If i put in 5 and put in 5 names the array is only 5x5 so it cuts some of the names off. Really new on arrays and even newer on two dimensional arrays. Thanks
    Code:
    #include<iostream>
    using namespace std;
    
    
    int main()
    {
        int number,i,j,k,l;
        char names[15][20];
        do
        {
            cout << "How many names would you like to enter(Must be less than 20): "<<endl;
            cin >> number;
            if(number < 0 || number > 20)
            {
                cout << "You have entered a number that is out of range"<<endl;
            }
        }while(number < 0 || number > 20);
        
        cout << "Please enter the names you would like to enter: " << endl;
        for(i=0; i < number; i++)
        {
            for(j=0; j < number; j++)
            {
            cin >> names[i][j];
            }
        }
        
        cout << endl;
        cout << "The names you entered were: " <<endl;
        for(k=0;k < number; k++)
        {
            for(l=0; l < number; l++)
            {
                cout << names[k][l] << " ";
            }
            cout << endl;
        }
    
    
    
    
        system("pause");
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    First thing you have your array dimensions backwards. It should be names[20][15], an array of 20 names of 15 characters.

    Next this:
    Code:
        for(i=0; i < number; i++)
        {
            for(j=0; j < number; j++)
            {
            cin >> names[i][j];
            }
        }
    is trying to retrieve single characters, not the entire name, you don't need the second loop. Also I recommend getline() instead of the extraction operator>>.

    Lastly this:
    Code:
        for(k=0;k < number; k++)
        {
            for(l=0; l < number; l++)
            {
                cout << names[k][l] << " ";
            }
    Is printing the first "number" of characters of the first "number" of arrays. Again you don't need the second loop, and you don't need the second array brackets[].


    Jim

  3. #3
    Registered User
    Join Date
    Oct 2013
    Posts
    44
    Thanks that worked like a champ. The problem im having right now is when i try to call the functions. Not sure if im doing it right. I can find all kinds of things about calling string functions but not character array and im pretty sure my sort function is wrong. its supposed to sort the names in alphabetical order but i think its comparing every letter of the names instead of the first letter or whole name. If i called the functions with just (names, number) id get a compiler error "argument type of "char(*)[15]" is incompatible with a parameter of type"char"
    Code:
    #include<iostream>
    using namespace std;
    void getnames(char names[], int number);
    void sortArray(char names[], int number);
    
    
    int main()
    {
        int number,i=0,j,k=0,l;
        char names[20][15];
        do
        {
            cout << "How many names would you like to enter(Must be less than 20): "<<endl;
            cin >> number;
            if(number < 0 || number > 20)
            {
                cout << "You have entered a number that is out of range"<<endl;
            }
        }while(number < 0 || number > 20);
        
        getnames(names[i], number);
    
    
        cout << endl;
        cout << "The names you entered were: " <<endl;
        for(k=0;k < number; k++)
        {
                cout << "\n "<<names[k];
            }
        cout <<endl;
        sortArray(names[i],number);
    
    
        cout << "The names in sorted order are: " << endl;
        for(i=0; i < number; i++)
        {
            cout << names[i] <<endl;
        }
    
    
    
    
    
    
        system("pause");
    }
    
    
    void getnames(char names[], int number)
    {
        int i=0;
    cout << "Please enter the names you would like to enter: " << endl;
        for(i=0; i < number; i++)
        {
            cin >> names[i];
            }
        return;
    }
    void sortArray(char names[], int number)
    {
        int temp;
        for(int i=0; i <= number; i++)
        {
            for(int j=0; j < number; j++)
            {
                if(names[j] >names[j+1])
                {
                    temp=names[j];
                    names[j]=names[j+1];
                    names[j+1]=temp;
                }
            }
        }
        return;
    }
    Last edited by tonedogz71; 11-16-2014 at 02:01 AM.

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Why aren't you using std::string?
    char arrays are dangerous and using std::cin >> with them even more so as it can lead to buffer overflows.
    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.

  5. #5
    Registered User
    Join Date
    Oct 2013
    Posts
    44
    The assignment called for storing the names in an array of characters. I need to look up the syntax for getline() if that would be better than cin. I've just always used cin.

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    std::cin is not safe for char arrays, because C arrays are a C construct and not a C++ construct. Essentially, you are learning C and not C++.
    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.

  7. #7
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    std::cin is not safe for char arrays
    This is not entirely true. The extraction operator can safely be used with character arrays but it does take extra work that is not required when using C++ strings. This extra work involves using the setw() manipulator to limit the number of characters being retrieved. I do however still recommend getline() since it enforces limiting the number of characters, where as the extraction operator doesn't require this limit. And I agree C++ strings are superior in most ways.

    Jim

  8. #8
    Registered User
    Join Date
    Oct 2013
    Posts
    44
    Why would an assignment call for using a 2-d array for storing single names. Doesn't make sense to me. I guess I could read it in as a string and use strcpy () to copy it to a char array

  9. #9
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Why would an assignment call for using a 2-d array for storing single names.
    Because you're storing the name of multiple people. Remember a C-string is an array, to store more than one C-string you need multiple array dimensions.

    So for two people Jim and tonedogz71 your array would look like:

    name[0][0] = 'J'
    name[0[1] = 'i'
    name[0][2] = 'm'
    name[0[3] = '\0'

    name[1][0] = 't'
    name[1][1] = 'o'
    ...
    name[1][9] = '1'
    name[1][10] = '\0'


    Jim

  10. #10
    Registered User
    Join Date
    Oct 2013
    Posts
    44
    Keep getting "Expression must be a modifiable value" in the bubble sort. Any suggestions?

    Code:
    #include<iostream>#include<iomanip>
    using namespace std;
    
    
    void getInput(char names[][15],int number);
    void bubbleSort(char names[][15], int number);
    char names[20][15];
    int i,j,number;
    
    
    int main()
    {
            do
        {
            cout << "How many names would you like to enter(Must be less than 20): "<<endl;
            cin >> number;
            if(number < 1 || number > 20)
            {
                cout << "You have entered a number that is out of range"<<endl;
            }
        }while(number < 1 || number > 20);
    
    
        getInput(names,number);    
    
    
        cout << endl;
    
    
        cout << "The names you entered were: " <<endl;
        for(i=0;i < number; i++)
        {
                cout <<names[i]<<endl;
        }
        cout <<endl;
    
    
        bubbleSort(names,number);
        cout<<"The sorted names are: " <<endl;
        for(i=0; i < number; i++)
            {
                cout<<names[i]<<endl;
        }
    
    
    system("pause");
    }
    
    
    
    
    
    
    void getInput(char names[][15],int number)
    {
        for(i = 0; i < number; i++)
            {
            cout << "Please enter the names you would like to enter(one word): " <<(i+1)<< endl;
            cin>>setw(16)>>(names[i]);
            }
    
    
    }
    void bubbleSort(char names[][15],int number)
    {
        char temp[15];
         for (int i = 1; i <= number; i++) 
         { 
            for (int j = 0; j < number-1; j++) 
                {
                    if(names[j]>names[j+1])
                    {
                        temp=names[j];
                        names[j]=names[j+1];
                        names[j+1]=temp;
                    }
                }
        }
    }

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You can initialise an array, you can assign to its elements if those are not arrays, but you cannot assign to an existing array. So, you have an array of arrays, but your swap is problematic because it swaps the elements of this array of arrays by assignment, but these elements are arrays.

    Given that these inner arrays store null terminated strings, one option is to use strcpy to perform the "assignment". Another option is to use memcpy to copy over the entire contents of the arrays.

    EDIT:
    Oh wait, this is C++. Why not use std::string instead of null terminated strings? In such a case your swap would work as expected, plus you can make use of std::swap.
    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

  12. #12
    Registered User
    Join Date
    Oct 2013
    Posts
    44
    Quote Originally Posted by laserlight View Post
    You can initialise an array, you can assign to its elements if those are not arrays, but you cannot assign to an existing array. So, you have an array of arrays, but your swap is problematic because it swaps the elements of this array of arrays by assignment, but these elements are arrays.

    Given that these inner arrays store null terminated strings, one option is to use strcpy to perform the "assignment". Another option is to use memcpy to copy over the entire contents of the arrays.

    EDIT:
    Oh wait, this is C++. Why not use std::string instead of null terminated strings? In such a case your swap would work as expected, plus you can make use of std::swap.

    i would use the string functions but i have to use a bubble sort to sort the names in alphabetical order

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by tonedogz71
    i would use the string functions but i have to use a bubble sort to sort the names in alphabetical order
    So... why does that stop you from using std::string?
    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

  14. #14
    Registered User
    Join Date
    Oct 2013
    Posts
    44
    if i change it to std::string i get the error "expression must be a modifiable value" in the bubblesort on all 3 lines
    Code:
    #include<iostream>
    #include<iomanip>
    #include<cstring>
    using namespace std;
    
    
    void getInput(string names[][15],int number);
    void bubbleSort(string names[][15], int number);
    string names[20][15];
    int i,j,number;
    
    
    int main()
    {
    		do
    	{
    		cout << "How many names would you like to enter(Must be less than 20): "<<endl;
    		cin >> number;
    		if(number < 1 || number > 20)
    		{
    			cout << "You have entered a number that is out of range"<<endl;
    		}
    	}while(number < 1 || number > 20);
    
    
    	getInput(names,number);	
    
    
    	cout << endl;
    
    
    	cout << "The names you entered were: " <<endl;
    	for(i=0;i < number; i++)
    	{
    			cout <<names[i]<<endl;
    	}
    	cout <<endl;
    
    
    	bubbleSort(names,number);
    	cout<<"The sorted names are: " <<endl;
    	for(i=0; i < number; i++)
    		{
    			cout<<names[i]<<endl;
    	}
    
    
    system("pause");
    }
    
    
    
    
    
    
    void getInput(char names[][15],int number)
    {
    	for(i = 0; i < number; i++)
    		{
    		cout << "Please enter the names you would like to enter(one word): " <<(i+1)<< endl;
    		cin>>setw(16)>>names[i];
    		}
    
    
    }
    void bubbleSort(string names[][15],int number)
    {
    	string temp[15];
    	 for (int i = 1; i <= number-1; i++) 
    	 { 
    		for (int j = 0; j < number-1; j++) 
    			{
    				if(names[j]>names[j+1])
    				{
    					temp=names[j];
    					names[j]=names[j+1];
    					names[j+1]=temp;
    				}
    			}
    	}
    }

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    You're not supposed to use a 2d array of strings.
    Think about it: a string is an array of chars, so to make a string the C-way, you'd write:

    char mystr[N];

    So if you want an array of strings, you'd make an array out of the array:

    char my_array_of_str[M][N];

    But since std::string is a string, you can have an array of those:

    std::string my_array_of_str[M];

    Again, the problem stems from the fact that you cannot assign a C-array to another C-array. This is fundamental flaw in the C programming language. You simply cannot do it.
    The best way to solve THAT (but not your problem), is to use std::array which is copyable as you would expect.
    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. Problem with reading 2 dimensional array in IO
    By Envynness in forum C Programming
    Replies: 8
    Last Post: 04-13-2011, 05:57 PM
  2. Problem within multi dimensional array
    By lolguy in forum C Programming
    Replies: 5
    Last Post: 12-26-2008, 08:02 AM
  3. Simple 2 dimensional array problem
    By AmbliKai in forum C Programming
    Replies: 4
    Last Post: 10-30-2007, 05:49 AM
  4. Need desperate help with two dimensional array problem
    By webvigator2k in forum C++ Programming
    Replies: 4
    Last Post: 05-10-2003, 02:28 PM
  5. 2 Dimensional array question/problem
    By lanchfn21 in forum C++ Programming
    Replies: 2
    Last Post: 01-23-2003, 11:15 AM