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!

user3073408
  • 13
  • 1
  • 1
  • 3
  • Is it a necessary constraint to use arrays instead of std::vector? and char* instead of std::string? – Constantin Dec 06 '13 at 07: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. – slim Dec 06 '13 at 07:46

2 Answers2

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] << ' ';
        }
    }
}
BoBTFish
  • 19,167
  • 3
  • 49
  • 76
  • unfortunately i can only use and 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 Dec 06 '13 at 08:16
  • @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 ``, or ``? 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). – BoBTFish Dec 06 '13 at 08:21
  • @user3073408 Also, is there a limit on the number of words? – BoBTFish Dec 06 '13 at 08:22
  • Ahh i don't know the difference , is different from them as well? It's either or , but definitely not . – user3073408 Dec 06 '13 at 08:24
  • @user3073408 Ok, that's fine. `` is the string utilities from `C`. In `C++` it should be called ``, so those two are basically the same. Unfortunately, you can't use `` 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. – BoBTFish Dec 06 '13 at 08:29
  • @user3073408 Is there a limit on the number of words? If not, this gets significantly more complicated, as you basically need to rewrite `std::vector`. – BoBTFish Dec 06 '13 at 08:35
  • the limit is not specified in the problem, but i guess i can limit it to 20 words max and each is 50 letters or less, it's supposed to be doable for beginners :D i think they are teaching us like that on purpose,they said if we get c++ we will learn the other languages more easily and quickly – user3073408 Dec 06 '13 at 08:46
  • @user3073408 Ok, I posted a solution where I guessed a limit of 10. Just swap the 10s for 20s. They are teaching you `C++` very badly. If they want you to learn this low level stuff, they should just teach you `C`, because this is a **really bad** (I can't stress that enough) way of doing this in `C++`. Learning how to do it right would be better to learn first, and learning how to write the library facilities comes later. They are doing it backwards, and missing out important things like how to avoid dangerous constructs (raw arrays! yuck). – BoBTFish Dec 06 '13 at 09:04
  • Don't worry i wont copy-paste the solution anywhere,it was a sample problem for practice but i had trouble writing it.Thank you very much for all the answers :) – user3073408 Dec 06 '13 at 09:23
0

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

Deidrei
  • 2,125
  • 1
  • 14
  • 14
  • I'm new to c++ so i don't know how to use these functions :/ Is there a solution using more basic language? – user3073408 Dec 06 '13 at 07:44
  • @user3073408: I suggest you read some books first, take a look at [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Deidrei Dec 06 '13 at 07:52