Read a whole sentence till i find a specific word


hi, i wanne read a sentence that is no more than 100 symbols and when it reads the word stop it ends reading the sentence.
1
2
3
4

char*text;
cin.getline(text, 100);

but how to do the part woth the word stop?
Well first off, avoid using char arrays, especially char pointers, and most importantly uninitialised char pointers.

getline() only stops on specific characters, not whole words.

So perhaps
1
2
3
4
5
6
7
8
string word;
string line;

while ( line.length()<100 && cin >> word && word != "stop" ) {
  if ( line.length() > 0 )
    line += " ";
  line += word;
}
we cants use strings in our course thats why
Perhaps you're on the wrong course then.

Your course seems to be "This course teaches you to run a marathon, but to create a level playing field, we start by breaking everyone's legs".

Your "tutor" is feeding you brain damage that's of little to no use in modern C++.

> we cants use strings in our course thats why
Well then
- replace .length with strlen()
- replace += with strcat()
- replace == with strcmp()

Consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <iomanip>
#include <cstring>

int main()
{
	const size_t MAXCH {100};
	const char* const stop {"stop"};

	char word[MAXCH] {};
	char line[MAXCH + 1] {};

	for (size_t linlen {}; linlen < MAXCH && (std::cin >> std::setw(MAXCH) >> word) && (std::strcmp(word, stop) != 0); linlen += std::strlen(word)) {
		if (linlen > 0) {
			strcat(line, " ");
			++linlen;
		}

		strcat(line, word);
	}

	std::cout << line << '\n';
}

Topic archived. No new replies allowed.