Thread: Reading a text file using stdin then traversing through multiple arrays

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    14

    Reading a text file using stdin then traversing through multiple arrays

    I got a text file that is a single line of a string. For example:
    Im John
    I need to read the file using stdin then traverse each characters into multiple arrays where each row shifts to the left by one character:
    row1 = [I, , m , , J , o , h , n]
    row2 = [ , m , , J, o , h, n , I ]
    row3 = [m , , J , o , h, n, I , ]
    row4 = [, , J , o , h , n , I , , m]
    ...
    rown = [n , I , , m , , J , o , h ]
    It is important to note the length of the arrays and number of arrays I create are variable that are dependent on the length of the string from the text file (n*n). In this case it would be 8*8 characters, so I need to create 8 arrays with 8 length each. Any help please?

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    624
    Code:
    #include <iostream>
    #include <string>
     
    inline char get_char_at(const std::string& s, int row, int col) {
        return s[(row + col) % s.size()];
    }
     
    int main() {
        std::string s;
        for (char ch; std::cin >> ch; )
            s.push_back(ch);
    
    
        for (int row = 0; row < int(s.size()); ++row) {
            for (int col = 0; col < int(s.size()); ++col)
                std::cout << get_char_at(s, row, col) << ' ';
            std::cout << '\n';
        }
    }
    The world hangs on a thin thread, and that is the psyche of man. - Carl Jung

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading from a text file with stdin
    By Befiscure45 in forum C++ Programming
    Replies: 7
    Last Post: 1 Week Ago, 01:55 PM
  2. Reading a text file into multiple nodes
    By e2076w in forum C Programming
    Replies: 1
    Last Post: 10-14-2009, 09:21 PM
  3. Reading Multiple Pieces of Data From Text File
    By bengreenwood in forum C++ Programming
    Replies: 3
    Last Post: 09-02-2009, 07:49 AM
  4. Reading Multiple Multi-Part Strings From a Text File
    By bengreenwood in forum C++ Programming
    Replies: 2
    Last Post: 06-02-2009, 10:43 AM
  5. traversing text file
    By AML24 in forum C++ Programming
    Replies: 8
    Last Post: 06-07-2006, 11:20 AM

Tags for this Thread