Store the contents of a file in a 2d char array

I'm a beginner at C++ and I'm having a hard time trying to store file values into a 2d character array.

I got it to work, kind of, but the problem is that because each line of text in the file isn't exactly 10 characters long it will add random characters to the end of words. I tried checking for a '\0' value and it hasn't worked, i've tried using getline and get for each char and it still doesn't work. I can't think of anything else to try to check for a new file line or anything of that sort.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  int size = 10;
  char fileInput[size];
  char largeInput[size][size];

  for(int i = 0; i < size; i++)
  {
     inputStream >> fileInput;

    for(int j = 0; j < size; j++)
    {
       largeInput[i][j] = fileInput[j];
       cout << fileInput[j];
    }

  }


Edit: typo
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
   vector<string> contents;            // this will hold the contents as a series of strings
   
   ifstream in( __FILE__ );            // open (this) file
   for ( string line; getline( in, line ); ) contents.push_back( line );       // read line by line

   int n;
   cout << "You read " << contents.size() << " lines\n";
   cout << "Which line would you like to see (counting from 1)? ";   cin >> n;
   if ( n >= 1 && n <= contents.size() ) cout << contents[n-1] << '\n';
}


You read 18 lines
Which line would you like to see (counting from 1)? 9
    vector<string> contents;            // this will hold the contents as a series of strings
Last edited on
Topic archived. No new replies allowed.