#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    6
    Rep Power
    0

    Question Reading Text File


    Hi there,

    I am not good at programming. I need to read a text file, say "a.txt", which contains some integer data (each integer is saperated by a space):

    0 1 2 3 4 5 6
    11 12 13 14 15 16 17
    111 222 333 444 555 666 777

    I need to read the data into a 2-dimensional array. Can anyone help me? Thanks!

    eclat:confused:
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    Representin' Quebec
    Posts
    106
    Rep Power
    12
    Ok, I'm not the best programmer either so ... but are you ok with i/o? Well I'll put up the whole thing (basic part)

    //Includes...

    ifstream in("a.txt", ios::in | ios::nocreate);

    // more stuff

    This is the real part:

    for(int i = 0; i <= n_rows; i++)
    for(int j = 0; j <= n_columns; i++) {
    in >> whatever;
    array[i][j] = whatever;
    }
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    3
    Rep Power
    0
    The insertion operator (>>) doesn't know the difference between a space and a newline, so unless you have the same number of values per line, and you know ahead of time how many that's going to be, you're not going to be able to read each line in your text file into a separate row in your array doing it that way.

    You'll need to use the getline() function to read each line of your text file into a string variable and then parse each one of these to get the integer values out.
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    Representin' Quebec
    Posts
    106
    Rep Power
    12
    Well look at his thing, it's a 3x7 number chart thing. So everyline is seven numbers. My thing would work and is less complicated! Just change n_rows to 3, and n_columns to 7.
  8. #5
  9. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    2
    Rep Power
    0
    why u don't use fopen?

    its much easier you can use fscanf for reading
    Last edited by St!ng; July 20th, 2003 at 10:57 AM.

IMN logo majestic logo threadwatch logo seochat tools logo