-1

I am writing a C++ Program The input string for the same includes a string which contains alphanumeric char, symbols, whitespaces. I need to take input till the end of line which signifies the end of input string

Tried using do while like below, but while (value != '\n' || value != '\0'); is never getting satisfied, and even after pressing enter the while loop doesn't exit

do
{
    cin >> value;
    inputString.push(value);
} while (value != '\n' || value != '\0');

Example of Input String -

I am :IronnorI Ma, i

P.S. - I can't use getline, string library due to some coding constraints applicable in coding contests

vatsalya_mathur
  • 325
  • 1
  • 3
  • 11

3 Answers3

1

cin >> value;, like all formatted input functions, skips all whitespace while looking for the next character to read. Whitespace includes '\n', so it will never be read.

To read all characters, including the whitespace, you can use an unformatted input function like cin.get(value) instead.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
1

The while condition can never be false and break the loop.

With value being equal to any other character than '\n' or '\0' it will obviously be true and the loop will continue.

But, assuming value is '\n'. The condition will evaluate to while ('\n' != '\n' || '\n' != '\0'), thus while (false || true), thus while (true).

Now assuming value is '\0': while ('\0' != '\n' || '\0' != '\0') is equal to while (true || false) is equal to while (true).

What you need (as condition) is something like while (! (value == '\n' || value == '\0')) or (probably better) while (value != '\n' && value != '\0').

  • i don't think that is the problem here the problem is that `cin` ignores whitespaces as pointed by @Bo Persson below So the check is never satisfied – vatsalya_mathur May 04 '18 at 09:40
  • 1
    It was *part of* the problem apparently. After all, you did change the operator in the while-condition from OR to AND, didn't you? ;-) – JackGoldfinch May 05 '18 at 07:32
  • yeah it was also a part of the problem, but that would had been easier to figure out once I was able to include the whitespaces from the input. Thanks :) – vatsalya_mathur May 08 '18 at 02:06
0

Had to ignore the whitespace '\n' that was there during the first input and then use cin.get() to get the whole line as a string

cin >> noOfTestCases >> ws;

do
{
  cin.get(value);
  inputString.push(value);
} while (value != '\n' && value != '\0');
vatsalya_mathur
  • 325
  • 1
  • 3
  • 11