Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sstream>
- using namespace std;
- /** Realiza la suma de una cadena de números dados en formato string, separados entre comas. */
- int Add(string);
- /** Devuelve el número de divisiones */
- int numPartes(string);
- /**
- * Función main de prueba
- */
- int main()
- {
- cout << "Prueba Add(): " << Add("") << endl << endl;
- cout << "Prueba Add( 2 ): " << Add("2") <<endl << endl;
- cout << "Prueba Add( 8347 ): " << Add("8347") <<endl << endl;
- cout << "Prueba Add( 5,4 ): " << Add("5,4") <<endl << endl;
- cout << "Prueba Add( 5,5,5,5,4,100 ): " << Add("5,5,5,4,5,100") << endl << endl;
- cout << "Prueba Add( 1,2,3,4,5,6,7,8,9,10,1000 ): " << Add("1,2,3,4,5,6,7,8,9,10,1000") << endl << endl;
- return 0;
- }
- /**
- * Realiza la suma de una cadena de números dados en formato string, separados entre comas.
- */
- int Add(string numeros){
- int NUMERO_PARTICIONES = numPartes(numeros); // ¿Cuántos números hay en la cadena?
- string parte[NUMERO_PARTICIONES];
- string auxiliar;
- int aux = 0;
- int pos, resultado = 0;
- /** Case para 'n' != 0 y 1 */
- if(numeros.find(',')!=-1){
- parte[0]=numeros;
- for( int a=1; aux!=-1; a++ ){
- aux=0;
- auxiliar=parte[a-1];
- pos = auxiliar.find(',');
- parte[a-1] = auxiliar.substr(aux,pos); // Parte dividida entre aux=0 y pos=posicionDeLaComa
- parte[a] = auxiliar.substr(pos+1,numeros.length()); // El resto de la cadena (desde pos+1 hasta el final)
- aux = parte[a].find(','); // -1 si no encuentra ','
- }
- }
- /** Case un solo numero */
- if(numeros.find(',')==-1 || numeros.length()==1){ // Si no hay ninguna coma, o solo tiene un valor
- parte[0]=numeros;
- for(int a=1;a<NUMERO_PARTICIONES;a++) parte[a]="";
- }
- /** Case ningún número */
- if(numeros.length()==0){
- return 0;
- }
- /** Conversión de strings a enteros y suma */
- for(int a=0; a<NUMERO_PARTICIONES; a++){
- std::stringstream(parte[a]) >> aux; // Convierte la string en un int.
- resultado += aux; // Se suma al resultado
- }
- return resultado;
- }
- /**
- * Devuelve el número de divisiones
- */
- int numPartes(string numeros){
- int aux, resultado = 0;
- string cortada = numeros;
- aux = cortada.find(',');
- while(aux!=-1){
- aux = cortada.find(',');
- cortada = cortada.substr(aux+1,cortada.length());
- resultado++;
- aux = cortada.find(',');
- }
- return resultado+1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement