how to wrap text into a 2D array

Hello,

I'm having a couple problems working with 2d arrays. My array is of size 5 rows and 5 columns. I want to gather a word from a file put it into an array and display it. I'm having trouble gathering the characters from the string in the file and putting it into my array. Is there a way i can loop it into the array? Here is what i have.

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{
char ch;
char array[5][5];
int row;
int col;

ifstream fin;
ofstream fout;

fin.open("input.txt");
fout.open("out.txt");

if (!fin)
    cout << "Input file did not open.";


fin.get(ch);


while (ch != '\n')
{
fin.get(ch);
}
for (row  = 0; row < 5; row++)
{
    for (col = 0; col < 5; col++)
        array [row][col] = ch;
}


for (row = 0 ; row <5; row++)
{
    for (col = 0; col < 5; col++)

        cout << array [row][col] << " " << endl;
}


    return 0;
}



I also have another question. After I get the chars into the array. I want to make sure there are no repeat letters. For instance, if my file word was "return" the input into the array would be [r][e][t][u][n] with the second "r" left out. I was thinking that what i should do is do a comparison. I'm not sure how to do this with a 2d array? or if i should do it while gathering and placing chars into my array or do it after (delete repeat chars)?

hi HPexpress

HPexpress wrote:
1
2
3
4
5
6
fin.get(ch);


while (ch != '\n')
{
fin.get(ch);

there are two calls to read the character from the stream. you should have missed the first character.

and as for looping it into the array, here's the logic. i'm using C, so i don't really know C++ syntax.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
for (row=0; row<5; row++)
{
    for (col=0; col<5; col++)
    {
        //read the character from stream
        
        //check if character is valid 
        if (...) //if invalid, take necessary action here
        {
            ...
        }
        else //if valid, store it
        {
            //store character into array[row][col]
        }
    }
}


there are lots of loopholes in the part where we read character from stream. we need to check for the validity in case, say, the stream has ended, etc.

to remove the repeats, you can either do it after the array has been filled or otherwise. either way, it works.

its best to perform the removal of recurring characters before the array creation. you can use the same loop above, and do a check with the existing array. compare between the character in stream and the array. if found, then do not store, and continue the loop.

hope this helps.
Topic archived. No new replies allowed.