Mixing cin and getline under Linux and Windows

戏子无情 提交于 2019-12-11 02:41:35

问题


I am aware of the common problem with mixing cin and getline. I believe this is different.

This is the program:

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;

int main() {
  int a;
  string line;
  cin >> a;
  printf("A is '%d'\n", a);
  getline(cin, line);
  printf("Line is '%s'\n", line.c_str());
  cout << cin.fail() << cin.eof() << cin.bad() << endl;
}

I also have a version written using istream::getline. I believe the results are the same in all input cases given here.

a.out < test1
A is '1'
'ine is ' abc 2
000

a.out < test2
A is '1'
Line is ' abc 2'
000

where test1 is $'1 abc 2\r\n' (9 bytes) and test2 is $'1 abc 2\n' (8 bytes).

I haven't explicitly done these tests under Windows, but I have a hunch that the output is "as intended" i.e. same as output of test 2.

My question is: explain the output of test 1. For example: why is printf output corrupt; is there a portability issue related to interpretation of line endings; how can the code be fixed with minimal change in logic.


回答1:


Under Linux, getline removes \n from the input stream. However, it does not remove the \r.

The carriage return (\r) returns the cursor to the beginning of the current line. So in the printf call, the STDOUT cursor is returned to the beginning of the line when it sees the \r. The next character it prints is the ', which overwrites the first character on the line (the L).

You do not see this behavior when there is no \r in the file.

Easy solution to fix this problem: manually check for \r when running under Linux and Unix.



来源:https://stackoverflow.com/questions/13003521/mixing-cin-and-getline-under-linux-and-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!