domenica 12 febbraio 2017

COMPITO 9 ( PICCIALLI , CHIANESE)

COMPITO 9 SCAMBIO ARREY MATRICE
#include<iostream>
#include<fstream>
#include<string>

#define MAX 100

using namespace std;

typedef char cstring[256];

void apriFile(ifstream &file);
void caricaFile(ifstream &file, string **mat, int &righe, int &colonne);
void stampa_lung_uguale(string **mat, int righe, int colonne);
void ordinaMatrice(string **mat, int righe, int colonne);
void stampaMatrice(string **mat, int righe, int colonne);
void scambiaArray(string*, string*, int);

int main(){
ifstream file;
string **mat;
int righe, colonne;

mat = new string*[MAX];
for (int i = 0; i < MAX; i++){
mat[i] = new string[MAX];
}

apriFile(file);
caricaFile(file, mat, righe, colonne);
ordinaMatrice(mat, righe, colonne);
stampa_lung_uguale(mat, righe, colonne);
stampaMatrice(mat, righe, colonne);
system("PAUSE");

return 0;
}

void apriFile(ifstream &file){
string percorso;

cout << "Inserire il percorso del file: ";
do{
cin >> percorso;
file.open(percorso, ios::in);
if (!file)
cout << "Errore nell'apertura del file, inserire un nuovo percorso: ";
} while (!file);

return;
}

void caricaFile(ifstream &file, string **mat, int &righe, int &colonne){
cstring temp;
char c;
int riemp = 0;
int row = 0, col = 0;

while (!file.eof()){
file.get(c);
if (c == ' '){
temp[riemp] = '\0';
mat[row][col] = temp;
col++;
riemp = 0;
}
else if (c == '\n'){
temp[riemp] = '\0';
mat[row][col] = temp;
col=0;
row++;
riemp = 0;
}
else{
temp[riemp] = c;
riemp++;
}
colonne = col + 1;
righe = row + 1;
}

return;
}

void stampa_lung_uguale(string **mat, int righe, int colonne){
int max = 0;
for (int i = 0; i < righe; i++){
for (int j = 0; j < colonne; j++){
if (mat[i][j].length()>max)
max = mat[i][j].length();
}
}

cout << "Le stringhe di lunghezza massima ("<<max<<") sono in posizione:\n";

for (int i = 0; i < righe; i++){
for (int j = 0; j < colonne; j++){
if (mat[i][j].length() == max)
cout << "[" << i << ", " << j << "]: "<<mat[i][j]<<"\n";
}
}
}

void ordinaMatrice(string **mat, int righe, int colonne){
int somma1, somma2;
int scambi;

do{
scambi = 0;
for (int i = 0; i < righe - 1; i++){
somma1 = 0;
somma2 = 0;
for (int j = 0; j < colonne; j++){
somma1 = mat[i][j].length();
somma2 = mat[i+1][j].length();
}
if (somma1 > somma2){
scambiaArray(mat[i], mat[i + 1], colonne);
scambi++;
}
}
} while (scambi > 0);

}

void stampaMatrice(string **mat, int righe, int colonne){
for (int i = 0; i < righe; i++){
for (int j = 0; j < colonne; j++){
cout << mat[i][j] << " ";
}
cout << endl;
}
}

void scambiaArray(string* vet1, string* vet2, int lung){
string temp;

for (int i = 0; i < lung; i++){
temp = vet1[i];
vet1[i] = vet2[i];
vet2[i] = temp;
}

}

Nessun commento :

Posta un commento