My assignment asks to find the common prefixes from user input, for example, user input -- "tiger" "teacup" "time" output : user inputs 3 strings and Common prefix is "t"
I have no idea to start with this coding since this assignment doesn't allow me to use an array and class.
and.. here is my starting..!
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string words;
string common;
cout <<"Please input the strings: "<< endl;
getline(cin,words);
for (int i=0; i<words.length(); ++i)
{
You can access words[i] to get the i'th letter (strings are basically fancy arrays).
Does that give you at least an idea of where to start?
In a nutshell, get one word. You now only have one word, so every letter is "common".
Then, when you get the next word, only save the letters that are in common with the existing common string (i.e. the previous word).
When you get the word after that, you repeat this, only saving the letters that are in common with the (now possibly reduced) common string.
Thee's multiple ways to actually get the first word from words. You can use a combination of string.find and string.substr to extract words (or, you can convert the string into a stringstream, then extract out each word with the >> operator).
You don't need to store the all the strings, only the previous one to compare to.
However, as the OP's code currently stands, there's no way to say what the number of words is before you actually get the words from the user, so basically all the words are being stored in the words array, presumably delimited by whitespace. The trick would then be to get n'th word out of the string to compare it to the (n-1)'th word.
but this assignment doesn't allow any #include other than <iostream> and <string> since its very beginners class..
Right now I'm stuck right here ; what should I put in the 'do-while' loop for extract the common prefix?
int main()
{
bool stop = false;
string s;
string com;
int longest=0;
int numberofstring = 0;
string longest_str;
cout <<" Please input string"<<endl;
do
{
getline(cin,s);
if(s.size()>longest). // *** here, I try to out put the longest string but it always output 'STOP'
{
longest_str = s;
}
com = s;
for(int i = 0; i<com.length(); ++i)
{
++numberofstring;
if (s == "STOP")
{
stop = true;
}
}