Here is my code, If you enter “Ctrl+Z” it should finish, but it will go into loop mode and it repeats writing the last word.
#include <iostream>
using namespace std;
int main()
{ char word[80];
do
{ cin >> word;
if (*word) cout << "\t\"" << word << "\"\n";
} while (*word);
}
By Pressing “Ctrl+Z” this simple program should end, but why it is not going in this way? what is problem with it?
Look at this code:
{ char line[80];
do
{ cin.getline(line,80);
if (*line) cout << "\t[" << line << "]\n";
} while (*line);
}
it is similar to the first code, but this time it is working fine and it will exit loop by pressing “Ctrl+Z”
So what is the exact problem with first code?
It doesn’t exit the loop because
*wordis not null-character;wordstill points to the buffer read in the previous iteration, and it does gets erased when you press Ctrl+Z.You should write the loop as:
then it should exit the loop once you press Ctrl+Z
Also, it is better to declare
wordasstd::stringinstead ofchar[80]: