Question

I need to write a program that has as input an array of words, each word is 50 characters or less. (I can only use <iostream> and <string.h>)

The sample input is : watch stumble student point welcome

my code:

char input[1000000];
for (int i = 0, i < 1000000, i++) {
    cin >> input[i];
}

Now how can I identify each word(max 50 letters per word) and store it in a separate string ,so that:

str1 = 'watch'
str2 = 'stumble'

and so on.

Then I have to find all words that start with a prefix that the user inputs, for example if the prefix is "stu" the output is: stumble student

I'd be really grateful if anyone can help in the next 1-2 hours!

Was it helpful?

Solution

For starters, read into a std::string, so you don't need to worry about the length. You do this is the loop condition, so you read and immediately check it succeeded:

std::string word;
while (std::cin >> word) // ...

This reads strings separated by whitespace (spaces, tabs, newlines, etc). I'd then store them into a std::vector, so you don't have to worry how many words there are:

std::vector<std::string> words;
std::string word;
while (std::cin >> word)
    words.push_back(word);

To then loop over this and print the words beginning with "stu", you have various options. I'm going to suggest using the Standard Library algorithm copy_if. This takes a predicate (checker function), and applies it to each element in the vector. If the predicate comes back true, it copies the element to somewhere else, in this case (and this is the only slightly fiddly bit), we copy to std::cout, using a special kind of iterator called an ostream_iterator:

std::copy_if(std::begin(words),
             std::end  (words),
             std::ostream_iterator<std::string>(std::cout, " "),
             [](const std::string& word){ return word.find("stu") == 0; });

This uses a few C++11 features (copy_if, lambdas, non-member begin/end). You could also write the bare loop yourself (prefer not to):

for (std::vector<std::string>::const_iterator it = words.begin();
     it != words.end();
     ++it)
{
    if (it->find("stu") == 0)
        std::cout << *it << ' ';
}

You could use similar techniques to read the input too, but I showed the more common way (in my experience) above. Some would argue this is preferable, but it uses more odd iterators:

std::vector<std::string> words;
std::copy(std::istream_iterator<std::string>(std::cin),
          std::istream_iterator<std::string>(),
          std::back_inserter(words));

istream_iterator is a way of treating an input stream like a container.

So that gives you two options:

write the raw loops yourself: while and for. This is how most people write it, especially "beginners", but I generally prefer to use the built in features to avoid the low level stuff. Think in terms of the concept you are applying, i.e. "I'm copy ing these words to the screen, if they begin with "stu"".

The other option is to use the facilities provided in the <algorithm> header. I like this option, but it does involve getting your head around some of the odd iterators.

Edit: By the way, the headers you will need are <algorithm>, <iostream>, <iterator>, <string> and <vector>. (You can drop <algorithm> and <iterator> if you write the raw loops).

Edit again: Ok, I hate myself for writing this, but here's a way of doing it with just C-style strings. You have to be VERY careful when working with naked arrays and pointers like this. I have commented the code to explain each step. I prefer not to just give a complete solution like this, but I'm not sure how to best explain each part otherwise. Please learn from it rather than just stealing it.

#include <cstring>
#include <iostream>

typedef char FixedLengthString [51]; // 50 chars plus NUL-terminator

int main()
{
    FixedLengthString words [10]; // assume you never have more than 10
                                  // if you have no limit, this is harder

    // need to do two things at once in the loop:
    //  - read no more than ten
    //  - read and check it succeeded
    int read = 0; // outside the loop, as we need it later
    for (; read < 10; ++read)
    {
        std::cin.width(50); // saves us from overflowing by reading too much
        std::cin >> words[read];

        // die if the read failed (end of input or something broke)
        if (!std::cin) break;
    }

    // loop over however many we successfully read
    for (int i = 0; i < read; ++i)
    {
        // compare the first 3 characters of the words with "stu"
        if (std::strncmp("stu", words[i], 3)==0)
        {
            std::cout << words[i] << ' ';
        }
    }
}

OTHER TIPS

You can use vector<string> to store the inputs. Then, using std::string::find() to find the match ones.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top