Advertisement
fcamuso

C++ lettura files CSV

Aug 11th, 2021
1,346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. //il file classifiche.txt contiene su ogni riga separati da punto e virgola:
  8. //cognome_alunno;posto in classifica (un intero);punteggio totalizzato (un numero con la virgola)
  9.  
  10. //l`obiettivo è quello di leggere e stampare i dati
  11. //SOLUZIONE:
  12. //usare getline con un TERZO parametro che specifica il carattere
  13. //(char, non string!) che fa da separatore dei dati
  14.  
  15. int main()
  16. {
  17.   ifstream leggi("classifiche.txt");
  18.  
  19.   if (!leggi)
  20.   {
  21.     cout << "Problemi apertura file ...";
  22.   }
  23.   else
  24.   {
  25.     string cognome="";
  26.  
  27.     string posto_classifica_str="";
  28.     int posto_classifica=0;
  29.  
  30.     string punteggio_str="";
  31.     double punteggio=0;
  32.  
  33.     while ( getline(leggi, cognome, ';') )
  34.     {
  35.  
  36.       getline(leggi, posto_classifica_str, ';');
  37.       try {
  38.         posto_classifica = stoi(posto_classifica_str);
  39.       }
  40.       catch (invalid_argument ecc_posto)
  41.       {
  42.         cout << "Errore di formato posto classifica\n";
  43.         break;
  44.       }
  45.  
  46.       getline(leggi, punteggio_str);
  47.       try {
  48.         punteggio = stod(punteggio_str);
  49.       }
  50.       catch (invalid_argument ecc_punteggio)
  51.       {
  52.         cout << "Errore di formato punteggio\n";
  53.         break;
  54.       }
  55.  
  56.       cout << "Giocatore: " << cognome << endl;
  57.       cout << "Posto Classifica: " << posto_classifica_str << endl;
  58.       cout << "Punteggio: " << punteggio_str << endl << endl;
  59.       cout <<string(40, '-')<<endl;
  60.     }
  61.  
  62.  
  63.     leggi.close(); leggi.clear();
  64.   }
  65.  
  66.   return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement