Reading in a sentence and end loop

I am trying to read in a sentence and end the loop with "done". It doesn't work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//
#include <iostream>
#include <cstring>              // declare strlen(), strcpy()

int main()
{
 using namespace std;
 int count = 0;

 char word[30] {};

 cin.get(word,30);
 while (strcmp(word,"done") != 0)
 {
    cout << word;
    ++count;
    cin.get(word,30);
    cin.get();
 }
  cout << "\nThere were " << count << " words.\n";
   	cin.get();
    cin.get();
    return 0;
}
You could try using std::string instead of c-string.
1
2
3
4
	string word;

	cin >> word;
	while (word != "done")

etc.
Last edited on
Hi,
I'm sorry I was unclear about the scope of the project. Your answer would be my first choice. There were two conditions to the project:

1. Use an array of char and a loop to read one word at a time until the word done is entered.

2. Use the strcmp() function to make the comparison test.

Thanks for the reply
I think the problem is likely that you aren't reading in individual words. You're reading in lines. std::istream::get, when used with a c-string, behaves a lot like std::getline, except that it will not remove the newline from the stream. Using the extraction operator (std::cin >> word) might make things easier for you, if not as safe.
Do the rules permit you to replace this
cin.get(word,30);
with this
cin >> word;
Yes
Everything works! Thanks for the help Chervil.
Topic archived. No new replies allowed.