Thread: 2D arrays

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    6

    Question 2D arrays

    I have a text file with "$" chars only in it, I need to put this file into a 2D array[25][50], then count how many $ chars there are in the file, and output file and count to screen, any clues???Please help!!

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    I may not understand the assignment, but here goes.

    Code:
    #include <cstdlib>
    #include <fstream>
    #include <cstring>
    using namespace std;
    
    int main()
    {
       char lines[25][50];
       char *filename = "sample.txt";
       int num_of_lines = 0;
       int count = 0;
       int i, j;
    
       ifstream in(filename);
       if (!in)
       {
          cout << "Could not open file:" << filename << endl;
          return 0;
       }
       while (in.getline(lines[num_of_lines],50))
       {
          num_of_lines++;
       }
       for (i=0; i<num_of_lines; i++)
       {
          cout << lines[i] << endl;
          for (j=0; j<strlen(lines[i]); j++)
             if (lines[i][j] == '$')
                count++;
       }
       cout << "$ found:" << count << endl;
       return 0;
    }

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Forgot to close the file. Add this before the "return" at the end.
    in.close();

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Or before the for-loop.

  5. #5
    Registered User
    Join Date
    Oct 2001
    Posts
    6

    .dat file

    This works excellent if I save file as txt file, but my file is a .dat file and it wont read file, I can't find why? any suggestions.

    Many thanx swoopy

  6. #6
    Registered User
    Join Date
    Oct 2001
    Posts
    6
    Ah, no probs....got it working now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with 2d arrays
    By thamiz in forum C Programming
    Replies: 25
    Last Post: 05-25-2008, 05:06 AM
  2. 2D Array's, assigning chars.
    By gman89 in forum C Programming
    Replies: 9
    Last Post: 04-26-2008, 11:03 PM
  3. Initialising 2D and 3D arrays
    By fry in forum C++ Programming
    Replies: 5
    Last Post: 08-01-2002, 04:34 AM
  4. Reading 2d arrays from file?
    By Ringhawk in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2002, 09:05 PM
  5. how can i pass 2d arrays
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 11-02-2001, 07:33 AM