HI,

if i have something like this

char string[16];
std::cin>>string;

and i type something and press "Enter" then std::cin would terminate, how do i get it to terminate when my first key input is "Enter" ?
because normally if i do that , input will not terminate and i will only move to a new line so how do i get it to terminate instead ?

Use std::string in lieu of char array.

>how do i get it to terminate when my first key input is "Enter" ?
cin skips leading whitespace by default, and Enter is whitespace. Ideally you would be using getline instead of the >> operator:

#include <iostream>

int main()
{
  const int size = 5;
  char word[size];

  std::cin.getline ( word, size );
  std::cout<<"'"<< word <<"'\n";
}

You can remove the leading whitespace rule for the >> operator, but it probably won't work as you expect in all cases:

#include <iomanip>
#include <iostream>

int main()
{
  const int size = 5;
  char word[size];

  std::cin>> std::noskipws >> std::setw ( size ) >> word;
  std::cout<<"'"<< word <<"'\n";
}

std::noskipws turns off the skipping of leading whitespace, and std::setw is used to avoid buffer overflow, which you should always do when reading input into bounded memory such as arrays.

>Use std::string in lieu of char array.
That won't solve the problem, but it's still a good idea.

does the std::noskipws make the >> operator ignore the rest of the whitespaces? because i dont want it to or i would have used getline instead.

>does the std::noskipws make the >> operator ignore the rest of the whitespaces?
I do believe I made it very clear that std::noskipws turns off the removal of leading whitespace. By specifying leading whitespace, I'm excluding internal whitespace.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.