• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

C++ string manipulation

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

ssjwizard

Has slightly less legible writing than Thideras
Joined
Mar 12, 2002
Ok guys so its late, im tired, and I just want this over with.
Ive got this bit of c++ that is crashing.

Code:
#include <string>
#include <iostream>

using namespace std;//declare namespace

int main(){
//declare variables
bool runit=true;
int opt;
string input,cleaned,upper,reverse;
int start,end;

do{//begin rerun loop
int words=1;
cout << "The program will take an input string, remove all leading and trailing spaces, count the digits and words" << endl;
cout << "Please enter an inital string value, ex. '    Hello world   ':";
getline(cin,input);//Get inital input
start=input.find_first_not_of(" ");//find the first real character
end=input.find_last_not_of(" ");//find the last real character
cleaned=(input.substr(start,end));//get the new clean string, from start to end
for (int i=0;i<input.size();i++){
	if (isspace(cleaned.at(i))){words++;}//if the char at (i) is a space; increase word count
}
for (int i=0;i<cleaned.size();i++){
	upper+=(toupper(cleaned.at(i)));//convert the char at (i) to upper; concantinate to new string
}
for (int i=(cleaned.size()-1);i>=0;i--){//start at the end and move to the beginning.
	reverse+=cleaned.at(i);//add the char at (i) to new string
}
//output
cout << "You entered the string: " << input << endl;
cout << "The cleaned string is: " << cleaned << endl;
cout << cleaned << " contains " << cleaned.size() << " Characters" << endl;
cout << "There are " << words << " words in this string" << endl;
cout << "Switched to upper case: " << upper << endl;
cout << "In reverse: " << reverse << endl;
cout << "Would you like to run the program again?\nEnter 1 to continue\nEnter 2 to exit\n";
cin >> opt;
if (opt!=1){runit=false;}//if the user enters anything other than 1 exit
}while(runit);
return 0;
}

Well thanks for taking the time to look over this.
 
At a glance, I think that this for loop is your problem.
Code:
for (int i=0;i<input.size();i++){
	if (isspace(cleaned.at(i))){words++;}//if the char at (i) is a space; increase word count
}

You're using input.size() to loop over cleaned. If input is ever longer than cleaned this would cause errors.
 
oh snap. I didnt even catch that last night.. Im sure thats a big part of it.


Sigh well exaustion has its wear on us all. That was the ONLY problem with the code....

Thanks again!
 
Last edited:
I'm glad it worked.

With these kind of mistakes, after the bit where I'm all "arg! How did I miss that!", I'm always relieved that it was something simple instead of it being some deep voodoo that I don't understand ;)

For the record, I looked at it late last night and didn't see anything wrong either.
 
Back