0

this program is supposed to output to the console a string of letters i type in, for example if i type in "im hungry" then its supposed to output im hungry to the console in a matrix for, if something i type in is too long then it carries over to the next line of the matrix

heres the code i have so far:

#include <iostream>
#include <string>

using namespace std;
#define N 6

//
// fill:
//
void fill(string s, int M[][N], int ROWS, int COLS)
{
    int i, r, c;
    s= "x";

    for (i=0, r=0; r < ROWS; r++)
    {
        for (c=0; c < COLS; c++)
        {
             M[r][c] = s[i];  // store ith character into matrix:

             i++; // next character:
             if (i == s.length())  // start-over if that was last char:
             i = 0;
        }
   }
} 

void print(int M[][N], int ROWS, int COLS)
{
  string s;
  s= "x";
  int r, c;
  for(r=0; r< ROWS; r++)
  {
     for(c=0; c < COLS; c++)
     {
       cout<<(char)M[r][c];
     }

 cout <<endl; 
  }
 }

//
// main:
//
int main()
{
    string s;
    getline(cin,s);
    int  M[N][N];
    int  M2[N][N];
    int  row, col, ROWS, COLS;
    fill(s, M, 1, 1);
    print(M, ROWS, COLS);

return 0;
 }

instead of outputting what I type in, it keeps outputting a matrix of random characters (same no matter what I type in) any suggestions on how I can fix this?

taocp
  • 23,276
  • 10
  • 49
  • 62
polishusar
  • 31
  • 5
  • 2
    Do you really need of the matrix? – Shoe Mar 22 '13 at 17:39
  • 2
    wow , the code is identical... –  Mar 22 '13 at 17:43
  • `M`, `ROWS`, and `COLS` are all uninitialized in `main()`. You only pass 1 to `fill()` for the `ROWS` and `COLS` parameters and then print the, still uninitialized, `M` array. Can I suggest a [Good C++ Book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? – Blastfurnace Mar 22 '13 at 17:45
  • 1
    guess he didnt like any of the answer last time – Green Demon Mar 22 '13 at 17:46
  • What's wrong with the answers you've got on the duplicate question you've been posting prior? You commented that you don't understate the meaning from the answer, so may be you have to investigate about some more basic things about C++ and usage of `std::string` class. – πάντα ῥεῖ Mar 22 '13 at 17:46

1 Answers1

0

If you don't really need of the matrix you can simply:

void print(string s, int limit, char endl = '\n') {
    if (limit == 0) return;
    if (s.length > limit) {
        for (int i = 0; i < s.length; i++) {
            std::cout << s[i];
            if (i % limit == 0)
                std::cout << endl;
    } else {
        std::cout << s;
    }
}

which will take the string and print it, in case it below the limit, or split it into different lines with the endl char.

Shoe
  • 74,840
  • 36
  • 166
  • 272