Inside Man
Inside Man

Reputation: 4297

Entering Ctrl+Z for ending reading words will cause a loop error

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?

Upvotes: 1

Views: 733

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

It doesn't exit the loop because *word is not null-character; word still 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:

while(cin >> word) { /* your code */ }

then it should exit the loop once you press Ctrl+Z

Also, it is better to declare word as std::string instead of char[80]:

std::string word; //#include <string>

while (cin >> word)
{  
  cout << "\t\"" << word << "\"\n";
}  

Upvotes: 2

Related Questions