[c][c++]Controllo dei tipi

Discuti dei problemi relativi alla programmazione nel tuo linguaggio preferito!

Moderatori: cb_123, thrantir, tonertemplum

[c][c++]Controllo dei tipi

Messaggiodi diegofio il 04 nov 2009, 22:20

Ciao a tutti siccome mi sto imparando il C++ e questo è un problema che ho trovato spiegato girovagando parecchio qua è là in rete, incollo la soluzione così poi se mi serve so dove ritrovarla (lo so, uso privato del mezzo pubblico :) )

in questo esempio banalissimo si invertono i valori di un array intero di N elementi, con N dimensione dell'array quindi naturale non zero.
(ps ha appena segnato sheva inter sotto godo come un riccio!!!!! :asd: :asd: :asd: :asd: )
il mio problema da totale niubbo consiste nel controllare che l'utente da tastiera digiti roba coerente, quindi non una stringa per N o un double quando richiedo un intero. lo so è roba facile ma ve l'ho detto che son niubbo.

beh questa è la soluzione

Codice: Seleziona tutto
/**
* inverte gli elementi di un array, dopo aver chiesto il numero di elementi dello stesso.
*/

#include <iostream>
#include <limits>
using namespace std;

int main()
{
   long double input;
   long unsigned int arrayLength;
   cout << "Inserisci il numero di elementi del tuo array\n";
   bool error;
   do
   {
      error = false;
      cin >>  input;
      arrayLength = (int) input;
      if (arrayLength <= 0)
      {
         error = true;
         cout << "Devi inserire un numero naturale maggiore di zero, riprova.\n";
      }
      else if (!cin.good())
      {
         error = true;
         cout << "Immetti un valore corretto. Riprova.\n";
         cin.clear();
         cin.ignore(numeric_limits<streamsize>::max(),'\n');
      }
   }
   while (error);

   long int array [arrayLength];

   cout << "Ora inizia ad inserire ogni singolo elemento, premendo invio dopo ognuno.\n";
   for (long unsigned int i = 0; i < arrayLength; i ++)
   {
      cin >> input;
      array[i] = (int) input;
   }

   for (long unsigned int i =0; i < arrayLength/2; i ++)
   {
      long int element = array[arrayLength - 1 - i];
      array[arrayLength - 1 - i] = array[i];
      array[i] = element;
   }

   for (long unsigned int i =0; i < arrayLength; i ++)
      cout << array[i] << "\n";
   return 0;
}


il cuore della cosa è dato da cin.good, cin.clear e cin.ignore, che si trovano spiegate in questo post (incollo casomai il foro linkato crepasse):
k let see if I can explain.

C++'s stream object are statefull - meaning that they kind of keep track of what is going on. The default state of in istream (like cin) is good. Meaning that it is ready to return data to you (even if it has to go out and wait to get some).

Now the >> operator is a formatted input operator. That means that it tried to parse out whatever kind of data you are asking for:

cin >> someString; -- tries to parse out a string
cin >> someInt; -- ties to parse out int
cin >> someDouble; -- ties to parse out a double.

Now strings are easy, pretty much anything before a white space character gets returned.
Integers are not quite so easy... suppose the buffer has 'H' as the next character... well this can't be made into an integer (at least not without some custom coding on your part). So cin puts the character back into the buffer and goes into an error state. -- This means that nothing else can read from cin until that error state is cleared!

So cin.clear() clears the error state but leaves the buffer intact -- which we will now need to deal with. Now how we deal with the error is up to us. we could just loop back and hope for the best. We could just ignore the first character and try again. We could try to parse a new kind of number (like maybe a double), We could parse it as a string an try to determine what mistake the user made and give them a meaningful message... all of this is up to us.

A common solution is to just clear the input buffer of its content and try again.

So that brings us to cin.ignore(). Now the syntax for cin.ignore() is normally cin.ignore(size, delimChar). Where size is the number of characters to ignore up to a delimChar.

so cin.ignore(5, '1'); will ignore all character up until the first '1' -- so if the buffer had "ABC1DEF" in it before the call, it would have "DEF" in it after the call. (note that it did not leave the delimChar in the buffer -- this is important). Now if the buffer had "ABCDEF123" in it, then after the call it would have "F123" in it since it only ignored the first 5 characters.

So if wanted to make sure that EVERYTHING in the buffer can get cleared then we need to find out how large the buffer might be. Thus there is "numeric_limits<streamsize>::max()" which gives us the maximum stream size.

So: cin.ignore(numeric_limits<streamsize>::max(),'\n') will ignore everything in the buffer up to and including the first newline character (or an EOF).


da notare inoltre che nel programma vengono convertiti dei duoble in int (la dimensione di un array deve essere intera).
ok finito. quando mi servirà sta cosa e rileggerò questo topic sheva mi farà rigodere di nuovo :lol: e hanno pure appena segnato i gunners :sisi: quasi quasi continuo a scrivere magari porta bene e la dinamo fa il secondo. ciao
diegofio
AmdPlanet Guru
AmdPlanet Guru
 
Messaggi: 9270
Iscritto il: 29 lug 2005, 09:55

 

Re: Controllo dei tipi in C e C++

Messaggiodi diegofio il 05 nov 2009, 00:28

bah faccio ammenda vada a quel paese anche l'inter!
diegofio
AmdPlanet Guru
AmdPlanet Guru
 
Messaggi: 9270
Iscritto il: 29 lug 2005, 09:55


Torna a Programmare

Chi c’è in linea

Visitano il forum: Nessuno e 1 ospite

cron