0

I'm taking a command and I want to store it as a vector of characters.

int main()
{
    vector<char> command;
    cout << "Reservations>>";
    char next;
    cin >> next;
    while (next !='\n'){
        command.push_back(next);
        cin >> next;
    }
    for(int i=0; i< command.size(); i++)
        cout << command[i];
}

But the while(next !='\n') is not working, as it keeps letting me type even though I've hit enter.

ST3
  • 8,826
  • 3
  • 68
  • 92
Will Nasby
  • 1,068
  • 2
  • 16
  • 39
  • You could just input a string and make a vector from it. – chris Jan 28 '13 at 05:49
  • Why not simply use: `std::vector;`?? – Alok Save Jan 28 '13 at 05:50
  • http://stackoverflow.com/questions/2765462/how-to-cin-space-in-c – jogojapan Jan 28 '13 at 05:52
  • http://stackoverflow.com/questions/9673708/tell-cin-to-stop-reading-at-newline – jogojapan Jan 28 '13 at 05:53
  • @WillNasby. Firstly, please never change a question so it includes the answers given, only to ask a follow-up question. Follow-up questions, if necessary, should be _separate_ questions, or possibly be handled in the comments to an accepted answer. Secondly: have you actually looked at the links I posted? They tell you anything you need to know about how to stop `std::cin` ignoring whitespace. – jogojapan Jan 28 '13 at 06:14
  • Sorry, I'm clearly new here, I'll delete the 2nd part. I got my answer from your 2nd link so I just assumed your first was a similar solution, sorry. – Will Nasby Jan 28 '13 at 06:20
  • `std::cin` uses the enter key as a input delimiter, I expect it would not make it to the inputted character. – Karthik T Jan 28 '13 at 05:52
  • @WillNasby check the links posted by jogojapan – Karthik T Jan 28 '13 at 06:02

2 Answers2

1

I would use this:

cout << "Reservations>>";
string str;
getline (std::cin, str);
vector<char> command(str.begin(), str.end());

getline as a default uses \r and \n as a delimiters, compared with cin which also use space. std::string is the most common char container, so I'm sure you don't need to convert it into vector, but I added fastest way, how to do it.

ST3
  • 8,826
  • 3
  • 68
  • 92
0

Get input into a string then iterator it? or just use std::string to store command?

int main()
{
  cout << "Reservations>>";
  std::string command;
  cin >> command;  
  std::cout << command << std::endl;

  return (0);
}

I am not sure why you use std::vector but below sample should work:

int main()
{
  std::vector<char> command;
  cout << "Reservations>>";
  std::string next;
  cin >> next;    
  for(size_t i = 0; i < next.size(); i++)
  {
    command.push_back(next.at(i));
  }

  for(int i=0; i< command.size(); i++)
  {
      cout << command[i];
  }

  return (0);
}
billz
  • 44,644
  • 9
  • 83
  • 100