2

I am a relative novice to programming in general and i am having trouble with this piece of code.

cout << "what would you like to have inside that?" << endl;
cout << "please enter a sentance" << endl; 
cin.sync();
cin >> time[d];

cout << "Is this what you wrote?" << endl;
cout << time[d]<< endl;

system("pause");

it doesn't go past the the space and only outputs before it.

  • 1
    What do you mean ***doesn't go past the space***? – A Person Jan 16 '14 at 01:16
  • 1
    `getline(std::cin, time[d])`. As far as `>>` is concerned, any whitespace is a delimiter. – cHao Jan 16 '14 at 01:16
  • 1
    Please don't use `sync()` if you don't know what it does. Also, formatted input is delimited by whitespace. – David G Jan 16 '14 at 01:16
  • 1
    possible duplicate of [Getting input from user using cin](http://stackoverflow.com/questions/2184125/getting-input-from-user-using-cin) – cHao Jan 16 '14 at 01:19

3 Answers3

4

std::cin considers all whitespace (spaces, newlines, tabs, etc.) to be "delimeters" between separate inputs. There are ways to change the delimeter, but you're probably better served by getline which defaults to newline as the delimeter (though you can optionally specify a different one).

MooseBoys
  • 6,641
  • 1
  • 19
  • 43
0

I believe you're looking for std::getline, as std::cin will treat any whitespace as a delimiter. Try this:

#include <iostream>
#include <vector>
#include <string>

int main()
{
  std::vector<std::string> time(1);
  size_t d = 0;

  std::cout << "What would you like to have inside of that?" << std::endl;
  std::cout << "Please enter a sentence: ";
  std::getline(std::cin, time[d]);

  std::cout << "Is this what you wrote?" << std::endl;
  std::cout << "[" << time[d] << "]" << std::endl;

  return 0;
}
rcv
  • 6,078
  • 9
  • 43
  • 63
0

Instead using cin to take input time[d], try using getline. You may modify your code as below -

 cout << "Please enter a sentence: ";
 std::getline(std::cin, time[d], delim);

Now it takes time[d] as string until the delimitation character delim is found. The delimitation character can be like \t, \n, etc.

If you don't specify delimitation character, it takes \n as default delimiter.

yuvi
  • 1,032
  • 1
  • 12
  • 22