Need help with 2D arrays

Mar 31, 2015 at 10:36pm
Hi everyone, im a beginner and a project Im working on has to have a function that copies a string to a 2D array row by row from an input of list of names by the user. This is the format it should be in, how would i complete this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

bool copyStr(const string& str, char array[][COL], int Rows);

int main()
{	
	system("pause");
	return 0;
}
bool copyStr(const string& str, char array[][COL], int Rows)
{

}
Last edited on Apr 1, 2015 at 4:06am
Mar 31, 2015 at 10:42pm
A string is a string. What do you mean by "row by row"?

Should you copy characters from a string into an array? What about too short and too long input? What are the rules for those?
Mar 31, 2015 at 10:45pm
sorry, yes character by character into a 2D array. The function copies as many characters as it can. If the array is bigger than the string then the function fills the unused positions with spaces. If the string is bigger than the array then the function stops copying as soon as the array is full.
Mar 31, 2015 at 10:49pm
How would you do it, if the destination were just a 1D array of chars?
Mar 31, 2015 at 10:57pm
char name[20] = "howard smith";
other than what my book mentions, i dont know how i would come about this problem.
along those lines?

for(row = 0;row < Rows; row++)
for(col = 0; col < COL; col++)

??
Last edited on Mar 31, 2015 at 11:15pm
Mar 31, 2015 at 11:08pm
That line declares an array and initializes its contents from a constant string literal.

You, however, already have an array and you have to copy characters from std::string object. A loop, perhaps?
Mar 31, 2015 at 11:14pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

const int COL = 6;
const char EMPTY = ' ';

bool copyStr(const string& str, char array[][COL], int Rows);

int main()
{
	string str;
	
	cout << "Enter a name: ";
	cin >> str;
	
	cout << copyStr << endl;
	system("pause");
	return 0;
}
bool copyStr(const string& str, char array[][COL], int Rows)
{
	for(int row = 0; row < Rows; row++)				
	{
		char s = array[row][0];		
		if(s == EMPTY) continue;			
		int col = 1;
		while(s == array[row][col] && col < COL)
			col++;
		if(col == COL) 
			return true;
	}
	return false;
}

this is what i got yesterday, but i dont think its correct
Apr 1, 2015 at 7:35am
Please, lets practice first with 1D array.
1
2
3
4
void copyStr( const std::string & src, char dst[], size_t capacity ) {
  // copy at most capacity characters from src to dst
  // if src.size() < capacity then fill remaining elements in dst with ' '
}

Can you implement that?
Topic archived. No new replies allowed.