0

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!

2
  • Is it a necessary constraint to use arrays instead of std::vector? and char* instead of std::string? Commented Dec 6, 2013 at 7:39
  • You really don't want str1='watch'; str2='stumble'; - this is almost never a good idea. Put them in an array or some other list data structure. Commented Dec 6, 2013 at 7:46

2 Answers 2

2

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] << ' ';
        }
    }
}
Sign up to request clarification or add additional context in comments.

9 Comments

unfortunately i can only use <iostream> and <string.h> my knowledge in c++ is really limited right now and i have to write the program on the lowest level possible :D Thank you for the long and descriptive answer!
@user3073408 Ok, I'll try to provide some more details to help you come up with an answer within your constraints. First, let me check. Is that header <string>, or <string.h>? It really matters, they are very different (and you should never use the second one in C++ anyway, which is why I ask, but let's not get into that right now).
@user3073408 Also, is there a limit on the number of words?
Ahh i don't know the difference , is <cstring> different from them as well? It's either <cstring> or <string.h> , but definitely not <string>.
@user3073408 Ok, that's fine. <string.h> is the string utilities from C. In C++ it should be called <cstring>, so those two are basically the same. Unfortunately, you can't use <string> which is the one with all the nice C++ std::string class and associated stuff. So you are being told to write C in C++. Now, please take this seriously: Your teacher is teaching you really bad C++. If (s?)he wants you to learn low-level C stuff, that's fine, but should be taught in C. Please remember, don't write "real" C++ (e.g. if you get a job doing it) the way you are being taught.
|
0

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

2 Comments

I'm new to c++ so i don't know how to use these functions :/ Is there a solution using more basic language?
@user3073408: I suggest you read some books first, take a look at The Definitive C++ Book Guide and List

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.