Friday, July 31, 2009

String manipulation C++?

Hi i am working on a small program where a user enters a string which should be more than 8 characters. Then once they have entered a string, the program should do the following:


1) output the size of the sentence


2) output the 1st 3rd 5th and 7th letter and append it to the end of the inputted sentence.





This is what i have done so far but i am getting errors and i am new to c++:





#include %26lt;iostream%26gt;


#include %26lt;string.h%26gt;


#include %26lt;sstream%26gt;


using namespace std;





int main()


{


int iQuit;


char str[7];


cout%26lt;%26lt; "Enter sentence \n";


getline(cin,str);


cout%26lt;%26lt; "Size of the sentence" %26lt;%26lt; str.length() %26lt;%26lt; endl;


cin %26gt;%26gt; iQuit;


return 0;


}





Can someone help on this and the second part please? i could probably do this in java but i need to do in C++.





I would appreciate it if someone can help me on tell me they have done in such a way?

String manipulation C++?
There are two main kinds of string in C++, the null terminated strings inherited from C and the C++ string object. Using the latter makes your assignment a cinch. Unless you are instructed otherwise you should begin to use string objects and move away from null terminated strings whenever possible.








#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





int main()


{


string input;





while (input.length() %26lt;= 8)


{


cout%26lt;%26lt; "Enter sentence at least 8 characters in length\n";





getline(cin, input);


}





cout%26lt;%26lt; "Size of the sentence = " %26lt;%26lt; input.length() %26lt;%26lt; endl;





input += input[2];


input += input[4];


input += input[6];





cout %26lt;%26lt; "appended sentence is: " %26lt;%26lt; input %26lt;%26lt; endl;





return(0);


}
Reply:Try this code for starters. Can you spot the changes?





#include %26lt;iostream%26gt;


#include %26lt;string.h%26gt;


#include %26lt;sstream%26gt;


using namespace std;





int main()


{


int iQuit;


string input;


cout%26lt;%26lt; "Enter sentence \n";


getline(cin, input);


cout%26lt;%26lt; "Size of the sentence " %26lt;%26lt; input.length() %26lt;%26lt; endl;


cin %26gt;%26gt; iQuit;


return 0;


}
Reply:You can't say str.length(). You have to use the function strlen(), like this:





cout%26lt;%26lt; "Size of the sentence" %26lt;%26lt; strlen(str) %26lt;%26lt; endl;





To output the 1st, 3rd, 5th and 7th letters you have to access them from the string/character-array. This is done like so: str[0] is the 1st. str[2] is the 3rd letter, etc.





Appending is easy. Just make a new character array that is bigger, copy the inputted string to it (using the strcpy function) and then assign the letters that you want to the new string.


No comments:

Post a Comment