Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sstream>
- using namespace std;
- int Add(string); /** Realiza la suma de una cadena de números dados en formato string, separados entre comas. */
- int numPartes(string); /** Devuelve el número de divisiones */
- int main(){ /**Función main de prueba*/
- cout << "Prueba Add(): " << Add("") << endl << endl << "Prueba Add( 2 ): " << Add("2") <<endl << endl << "Prueba Add( 8347 ): " << Add("8347") <<endl << endl; << "Prueba Add( 10\\n8 ): " << Add("10\n8") <<endl << endl
- << "Prueba Add( 8,400 ): " << Add("8,400") <<endl << endl<< "Prueba Add( 5,5\\n5,4,5\\n100 ): " << Add("5,5\n5,4,5\n100") << endl << endl<< "Prueba Add( 1,2,3\\n4\\n5,6,7,8,9,10\\n1000 ): "
- << Add("1,2,3\n4\n5,6,7,8,9,10\n1000") << endl << endl;
- return 0;}
- int Add(string numeros){ /**Realiza la suma de una cadena de números dados en formato string, separados entre comas.*/
- int NUMERO_PARTICIONES = numPartes(numeros),pos, pos2, posBueno, resultado = 0,aux = 0,aux2; string parte[NUMERO_PARTICIONES],auxiliar;
- if(numeros.find(',')!=-1){ parte[0]=numeros;
- for( int a=1; aux!=-1 || aux2!=-1; a++ ){
- auxiliar = parte[a-1]; aux = 0; pos = auxiliar.find(','); pos2 = auxiliar.find("\n");
- if(pos!=-1 && pos2!=-1){
- if(pos<pos2) posBueno=pos; else posBueno=pos2;
- parte[a-1] = auxiliar.substr(aux, posBueno);
- parte[a] = auxiliar.substr(posBueno+1,auxiliar.length());}
- if(pos==-1 && pos2!=-1){
- parte[a-1] = auxiliar.substr(aux, pos2);
- parte[a] = auxiliar.substr((pos>pos2?pos:pos2)+1,auxiliar.length());}
- aux = parte[a].find(','); aux2 = parte[a].find("\n"); }}
- if(NUMERO_PARTICIONES==2){
- parte[0] = numeros.substr(0,(numeros.find("\n")==-1?numeros.find(','):numeros.find("\n")));
- parte[1] = numeros.substr((numeros.find("\n")==-1?numeros.find(','):numeros.find("\n"))+1,numeros.length());}
- if((numeros.find(',')==-1 && numeros.find("\n")==-1) || numeros.length()==1){parte[0]=numeros;}
- if(numeros.length()==0){return 0;}
- for(int a=0; a<NUMERO_PARTICIONES; a++){
- std::stringstream(parte[a]) >> aux;
- resultado += aux;}
- return resultado;
- }
- int numPartes(string numeros){ /**Devuelve el número de divisiones*/
- int aux, aux2, resultado = 1;string cortada = numeros;
- aux = cortada.find(',');aux2 = cortada.find("\n");
- while(aux!=-1 || aux2!=-1){
- if(aux!=-1 && aux2!=-1) {cortada = cortada.substr((aux<aux2?aux:aux2)+1,cortada.length());}
- else cortada = cortada.substr((aux>aux2?aux:aux2)+1,cortada.length());
- resultado++;aux = cortada.find(',');aux2 = cortada.find("\n");}
- return resultado;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement