How do I input variables using cin without creatin

2019-01-04 15:00发布

Whenever I input a variable using cin, after one hits enter it automatically goes to a new line. I'm curious if there's a way to use cin without having it go to a new line. I'm wanting to cin and cout multiple things on the same line in the command prompt. Is this possible?

7条回答
倾城 Initia
2楼-- · 2019-01-04 15:44

As others have noted, you can't do this with cin, but you could do it with getchar(). What you would have to do is:

  1. collect each character individually using getchar() (adding each to the end of a string as it is read in, for instance), then
  2. after reading each character, decide when you've reached the end of one variable's value (e.g. by detecting one or more ' ' characters in the input, if you're reading in int or double values), then
  3. if you've reached the end of the text for a variable, convert the string of characters that you've built into a variable of the appropriate type (e.g. int, double, etc.), then
  4. output any content onto the line that might be required, and then
  5. continue for the next variable that you're reading in.

Handling errors robustly would be complicated so I haven't written any code for this, but you can see the approach that you could use.

查看更多
登录 后发表回答