elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Los 10 CVE más críticos (peligrosos) de 2020


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  Problema con matriz char
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Problema con matriz char  (Leído 1,773 veces)
novatus84

Desconectado Desconectado

Mensajes: 18


Ver Perfil
Problema con matriz char
« en: 12 Diciembre 2014, 21:51 pm »

Muy buenas no consigo acabar este programa:
que me saque la matriz de 10*10 con palabras de un archivo y en los espacios me ponga una letra aleatoria me saca las palabras tal cual, llevo un rato volviéndome loco y no doy con el problema.

Código
  1. #include <vector>
  2. #include <iostream>
  3. #include <fstream>
  4. #include <string>
  5. #include <cstdio>
  6. #include <cstdlib>
  7. #include <ctime>
  8. #include <random>
  9.  
  10. using namespace std;
  11.  
  12. string filename = "words.txt";
  13. void error(const string&);
  14.  
  15. vector<string> load_vector(const string& filename) {
  16.  
  17.    vector<string> vi;
  18.  
  19.    ifstream ifile {filename};
  20.    if (!ifile)
  21.        error("load_vector cannot open the file " + filename);
  22.    copy(istream_iterator<string>(ifile), istream_iterator<string>(), back_inserter(vi));
  23.  
  24.    return vi;
  25. }
  26.  
  27. void error(const string& s) {
  28.    cerr << "Error: " << s << endl;
  29.    exit(EXIT_FAILURE);
  30. }
  31.  
  32. void aleatorio (int HEIGHT, int WIDTH,const char* puzzle[HEIGHT][WIDTH]) {
  33.  
  34.    srand(time(NULL)); //inicializamos semilla
  35.    string random;
  36.    for (int i = 0; i < HEIGHT; i++) {
  37.        for (int j = 0; j < WIDTH; j++) {
  38.            random = 'A' + (rand() % 26);
  39.            if (puzzle[i][j] == " ") {
  40.                puzzle[i][j] = random.c_str();
  41.            }
  42.        }
  43.  
  44.    }
  45. }
  46.  
  47. char wordToMatrix(int HEIGHT, int WIDTH) {
  48.  
  49.    char puzzle[HEIGHT][WIDTH];
  50.    int filarand = 0;
  51.    vector<string> load_vector(const string&);
  52.    vector<string> words = load_vector(filename);
  53.    string aux;
  54.    char empty = ' ';
  55.    const char* aux2;
  56.    char random;
  57.    char espacio = ' ';
  58.  
  59.    //Inicializamos matriz
  60.    for (int i = 0; i < HEIGHT; i++) {
  61.        cout << endl;
  62.        for (int j = 0; j < WIDTH; j++) {
  63.            puzzle[i][j] = '1';
  64.            cout << puzzle[i][j];
  65.        }
  66.    }
  67.  
  68.  
  69.    filarand = rand() % 10;
  70.    //cout << filarand << endl;
  71.  
  72.    for (int i = 0; i < 10; i++) {
  73.        filarand = rand() % 10;
  74.        cout << "" << endl;
  75.        for (int j = 0; j < words[i].size(); j++) {
  76.            if (words[i].size() < 10) {
  77.                    //aux2 = words[i].substr(j,1);
  78.                    aux = words[i].substr(j,1);
  79.                    puzzle[i][j] = aux[0];
  80.                    cout << puzzle[i][j];
  81.            }
  82.        }
  83.    }
  84.  
  85.    for (int i = 0; i < 10; i++) {
  86.        //cout << endl;
  87.        for (int j = 0; j < 10; j++ ) {
  88.            if (puzzle[i][j] == '1') {
  89.                random = 'A' + (rand() % 26);
  90.                puzzle[i][j] = random;
  91.                //cout << puzzle[i][j];
  92.            }
  93.        }
  94.    }
  95.  
  96.    /*for (int i = 0; i < HEIGHT; i++) {
  97.         cout << endl;
  98.         for (int j = 0; j < WIDTH; j++) {
  99.             random = 'A' + (rand() % 26);
  100.             if (puzzle[i][j] == espacio) {
  101.                 puzzle[i][j] = random;
  102.                 cout << puzzle[i][j];
  103.             }
  104.         }
  105.        
  106.     }*/
  107.  
  108.    return puzzle[HEIGHT][WIDTH];
  109.  
  110.  
  111. }
  112.  
  113.  
  114. int main() {
  115.  
  116.    int HEIGHT = 10;
  117.    int WIDTH = 10;
  118.  
  119.    char puzzle[HEIGHT][WIDTH];
  120.  
  121.    srand(time(NULL));
  122.    wordToMatrix(10,10);
  123.  
  124.    /*for (int i = 0; i < HEIGHT; i++) {
  125.         for (int j = 0; j < WIDTH; j++) {
  126.             cout << puzzle[i][j] << endl;
  127.         }
  128.     }*/
  129.  
  130.  
  131.  
  132.    return 0;
  133. }


En línea

eferion


Desconectado Desconectado

Mensajes: 1.248


Ver Perfil
Re: Problema con matriz char
« Respuesta #1 en: 14 Diciembre 2014, 16:27 pm »

Código
  1. void aleatorio (int HEIGHT, int WIDTH,const char* puzzle[HEIGHT][WIDTH])

Esa cabecera está mal. El valor de WIDTH en puzzle[HEIGHT][WIDTH] debe poder conocerse en tiempo de compilación, que no de ejecución, para que el código pueda crear el juego de instrucciones adecuado.

Código
  1. string random;
  2. // ...
  3. puzzle[i][j] = random.c_str();

Esto también está mal... ahí estás copiando en puzzle[j] el punter interno del string... una vez sales de ese bucle y "random" deja de existir, esa posición de memoria deja de ser válida. Ahí tendrías que copiar el string.

Código
  1. char wordToMatrix(int HEIGHT, int WIDTH) {
  2. char puzzle[HEIGHT][WIDTH];

Te digo lo mismo que en el primer punto, lo correcto es que, en este caso, tanto HEIGHT como WIDTH sean conocidas en tiempo de compilación, si ambas variables han de ser dinámicas lo lógico es que reserves memoria con "new".

Y bueno, no entro en más detalle porque no tengo ni compilador ni depurador a mano.

A ver si alguien más se anima.

Un saludo.


En línea

novatus84

Desconectado Desconectado

Mensajes: 18


Ver Perfil
Re: Problema con matriz char
« Respuesta #2 en: 14 Diciembre 2014, 23:11 pm »

ya lo tengo jejejejej, ahora me faltarían mejorar algún cosilla, meter las palabras en diagonal o en vertical, y mas jodido que seria una función para mostrar u ocultar las palabras usadas para el relleno de tal forma que pueda imprimír la solución sin las palabras aleatorias o con ellas tambien, estoy perdido no doy mas de mi jejejejeje
Código
  1. #include <vector>
  2. #include <iostream>
  3. #include <fstream>
  4. #include <string>
  5. #include <cstdio>
  6. #include <cstdlib>
  7. #include <ctime>
  8. #include <random>
  9.  
  10. using namespace std;
  11.  
  12. string filename = "words.txt";
  13. ifstream ifile {filename};
  14. void error(const string&);
  15.  
  16. vector<string> load_vector(const string& filename) {
  17.  
  18.    vector<string> vi;
  19.  
  20.    if (!ifile)
  21.        error("load_vector cannot open the file " + filename);
  22.    copy(istream_iterator<string>(ifile), istream_iterator<string>(), back_inserter(vi));
  23.  
  24.    return vi;
  25. }
  26.  
  27. void error(const string& s) {
  28.    cerr << "Error: " << s << endl;
  29.    exit(EXIT_FAILURE);
  30. }
  31.  
  32. void aleatorio () {
  33.    int HEIGHT = 15;
  34.    int WIDTH = 15;
  35.    int wordsize = 0;
  36.    int wordPos = 0;
  37.    char puzzle[HEIGHT][WIDTH];
  38.    bool okWord;
  39.  
  40.    srand(time(NULL)); //inicializamos semilla
  41.  
  42.    char random;
  43.    int filarand = 0;
  44.  
  45.    vector<string> load_vector(const string&);
  46.    vector<string> words = load_vector(filename);
  47.    vector<string> auxWords;
  48.    string enteredWord;
  49.    string aux;
  50.  
  51.    //Inicializamos matriz
  52.    for (int i = 0; i < HEIGHT; i++) {
  53.        for (int j = 0; j < WIDTH; j++) {
  54.            puzzle[i][j] = ' ';
  55.        }
  56.    }
  57.  
  58.    for (int i = 0; i < HEIGHT; i++) {
  59.        for (int j = 0; j < WIDTH; j++) {
  60.            random = 'A' + (rand() % 26);
  61.            puzzle[i][j] = random;
  62.        }
  63.    }
  64.  
  65.    for (int i = 0; i < HEIGHT; i++) {
  66.        filarand = rand() % 15;
  67.        wordsize = WIDTH - words[i].size() - 1;
  68.        wordPos = rand() % wordsize;
  69.        for (int j = 0; j < words[i].size(); j++) {
  70.            if (words[i].size() < 10) {
  71.                aux = "";
  72.                aux = words[i].substr(j,1);
  73.                puzzle[filarand][wordPos + j] = aux[0];
  74.            }
  75.        }
  76.    }
  77.  
  78.    for (int i = 0; i < HEIGHT; i++) {
  79.        for (int j = 0; j < WIDTH; j++) {
  80.            cout << puzzle[i][j];
  81.            cout << "  ";
  82.        }
  83.        cout << endl;
  84.    }
  85.  
  86.    auxWords = words;
  87.  
  88.    do {
  89.        cout << "Introduce una palabra: ";
  90.        cin >> enteredWord;
  91.  
  92.        for (int i = 0; i < auxWords.size(); i++) {
  93.            if (enteredWord == auxWords[i]) {
  94.                okWord = true;
  95.                auxWords.erase(auxWords.begin() + i);
  96.                break;
  97.            }
  98.        else {
  99.            okWord = false;
  100.        }
  101.        }
  102.  
  103.        if (okWord == true) {
  104.            cout << "Palabra " << enteredWord << " correcta" << endl;
  105.        }
  106.        else if (enteredWord != "FIN") {
  107.            cout << "Palabra " << enteredWord << " incorrecta" << endl;
  108.        }
  109.    } while (enteredWord != "FIN");
  110. }
  111.  
  112. /*char wordToMatrix(int HEIGHT, int WIDTH, char puzzle) {
  113.    
  114.     int filarand = 0;
  115.     vector<string> load_vector(const string&);
  116.     vector<string> words = load_vector(filename);
  117.     string aux;
  118.     char empty = ' ';
  119.     const char* aux2;
  120.     char random;
  121.     char espacio = ' ';
  122.     char puzzle[HEIGHT][WIDTH];
  123.    
  124.     filarand = rand() % 10;
  125.     //cout << filarand << endl;
  126.    
  127.     for (int i = 0; i < 10; i++) {
  128.         filarand = rand() % 10;
  129.         cout << "" << endl;
  130.         for (int j = 0; j < words[i].size(); j++) {
  131.             if (words[i].size() < 10) {
  132.                     //aux2 = words[i].substr(j,1);
  133.                     //aux = words[i].substr(j,1);
  134.                     //puzzle[i][j] = aux[0];
  135.                 puzzle[i][j] = words[i].substr(j,1).c_str();
  136.                     cout << puzzle[i][j];
  137.             }
  138.         }
  139.     }
  140.    
  141.     for (int i = 0; i < 10; i++) {
  142.         //cout << endl;
  143.         for (int j = 0; j < 10; j++ ) {
  144.             if (puzzle[i][j] == '1') {
  145.                 random = 'A' + (rand() % 26);
  146.                 puzzle[i][j] = random;
  147.                 //cout << puzzle[i][j];
  148.             }
  149.         }
  150.     }
  151.    
  152.     for (int i = 0; i < HEIGHT; i++) {
  153.         cout << endl;
  154.         for (int j = 0; j < WIDTH; j++) {
  155.             random = 'A' + (rand() % 26);
  156.             if (puzzle[i][j] == espacio) {
  157.                 puzzle[i][j] = random;
  158.                 cout << puzzle[i][j];
  159.             }
  160.         }
  161.        
  162.     }
  163.    
  164.     return puzzle[HEIGHT][WIDTH];
  165.  
  166.    
  167. }*/
  168.  
  169.  
  170. int main() {
  171.  
  172.    int HEIGHT = 10;
  173.    int WIDTH = 10;
  174.  
  175.    char puzzle[HEIGHT][WIDTH];
  176.  
  177.    srand(time(NULL));
  178.    aleatorio();
  179.    //wordToMatrix(10, 10, puzzle[HEIGHT][WIDTH]);
  180.  
  181.    /*for (int i = 0; i < HEIGHT; i++) {
  182.         for (int j = 0; j < WIDTH; j++) {
  183.             cout << puzzle[i][j] << endl;
  184.         }
  185.     }*/
  186.  
  187.  
  188.  
  189.    return 0;
  190. }
  191.  
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
duda doble puntero char a matriz de char
Programación C/C++
neo_from_cs_matrix 3 6,021 Último mensaje 5 Septiembre 2011, 03:53 am
por rir3760
Lectura de matríz de char como char** o DWORD*
Programación C/C++
david_BS 3 3,239 Último mensaje 20 Febrero 2012, 20:49 pm
por Eternal Idol
Convertir matriz Char a Int con atoi
Programación C/C++
jfap45 5 5,969 Último mensaje 9 Agosto 2012, 02:46 am
por BlackZeroX
Pasar matriz char a una función como referencia
Programación C/C++
KISKE 2 7,275 Último mensaje 18 Junio 2013, 13:07 pm
por KISKE
Formas de guardar en una matriz de char un string
Programación C/C++
DarkSeer 3 1,802 Último mensaje 24 Enero 2017, 09:21 am
por MAFUS
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines