-3

I tried looking on the internet but I've not seen an answer.

So I have to cin a char with multiple words, like "Cars have four wheels." And I need to take every word and cout him. I learned at school that you can do this:

char a[100][20];
cin.getline(a, 100);

But it doesn't work. What's the proper way to cin a char with multiple words separate by a space;

This is the exact code with the error

Marek R
  • 32,568
  • 6
  • 55
  • 140
Loukas
  • 29
  • 1
  • 4
  • Does [this](https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces) help? Or, if you _have_ to use `char` arrays instead of `std::string`... Are you sure school said that you can call `getline` on an array of arrays? – Nathan Pierson Nov 10 '21 at 15:53
  • `std::string word; while (std::cin >> word) { std::cout << word << '\n'; }` – Some programmer dude Nov 10 '21 at 15:55
  • As for your error, `a` is an array *of arrays* of characters. while `cin.getline()` expects an array of characters. I.e. something like `a[0]` or `a[1]`. – Some programmer dude Nov 10 '21 at 15:55
  • Please [edit] this question to include the code and error you are talking about, as actual text. This question will lose all value once imgur decides to delete that image. – Drew Dormann Nov 10 '21 at 16:01
  • https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question – Marek R Nov 10 '21 at 16:22
  • `a` has wrong type `char[100][10]`, which can't be implicitly converted to `char *` expected by `cin.getline`! – Marek R Nov 10 '21 at 16:23
  • @Loukas: Hi, may I know if your question has been solved? – Minxin Yu - MSFT Nov 16 '21 at 05:49

1 Answers1

0

You can try using std::istringstream for parsing the words.

std::vector<std::string> word_database;
std::string text_line;
while (std::getline(std::cin, text_line))
{
    std::string word;
    std::istringstream text_stream(text_line);
    while (text_stream >> word)
    {
        word_database.push_back(word);
    }
}

In the above code, one line of text is input to the text_line variable.

An istringstream is created using the line of text. The "words" are extracted from the text stream using operator>>. The words are appended to the database.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154