Monday, July 27, 2009

Trying to reverse name C++ here is what I have so far... (from reverse sentence lab)?

ok first off how to I define the string to stop at a comman ","? thanks





~Dan~





#include %26lt;cstdlib%26gt;


#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;


#include %26lt;string%26gt;


using namespace std;








int main()


{


//Local constants


const char SENTINEL = ',';





//Local variables


string wholename;


int length;


int comma;


string firstname;


string lastname;


string finalname;


int counter;


string rS;














//Input ten numbers


cout%26lt;%26lt;"Enter your name (Last, First): " %26lt;%26lt;endl;


getline(cin, wholename, '\n');





//Compute average


length=length-comma;


for (counter=(comma+2); counter%26gt;=0; counter--)


{


rS+=wholename[counter];


}


firstname = firstname - SENTINEL








//distance


cout%26lt;%26lt;"Your name reversed is: " %26lt;%26lt;endl;


cout%26lt;%26lt;rS%26lt;%26lt;endl;











//Indicate to OS succesful termination of program


return 0;





} //End main








ok first off how to I define the string to stop at a comman ","

Trying to reverse name C++ here is what I have so far... (from reverse sentence lab)?
Actually, why aren't you using what is already built into std::string? Something like:





#include %26lt;iostream%26gt;


#include%26lt;iomanip%26gt;


#include %26lt;string%26gt;





using namespace std;





int main(int argc, char *argv[])


{


string wholename, firstname, lastname;





cout%26lt;%26lt;"Enter your name (Last, First): " %26lt;%26lt;endl;





getline(cin, wholename, '\n');





size_t commaPos = wholename.find(',');





if (commaPos == string::npos) //no comma in str


{


cout %26lt;%26lt; "invalid input\n";


exit(EXIT_FAILURE);


}





firstname = wholename.substr(commaPos + 1, wholename.length() - 1);


lastname = wholename.substr(0, commaPos);





cout %26lt;%26lt; firstname %26lt;%26lt; " " %26lt;%26lt; lastname %26lt;%26lt; endl;





return(EXIT_SUCCESS);


}
Reply:Why arent you using a simple stack?
Reply:First off this code will not compile. Comma and Length are not initialized, meaning they don't have any value when you use them. Also your comments don't seem to talk about what is going on in your program. To answer your question, if you want to stop at a comma which i guess means you what to break up the string at the comma, then use a for loop to search for the comma, and record the number where the comma is in the string, then you should be able to break up the string how ever you would like. Or you could use some regular expressions to find it and collect the parts of the string you want.

online survey

No comments:

Post a Comment