在Linux和Windows下混合cin和getline [英] Mixing cin and getline under Linux and Windows
问题描述
我知道混合cin和getline的常见问题。我相信这是不同的。
这是程序:
#include< iostream>
#include< cstdio>
#include< string>
using namespace std;
int main(){
int a;
string line;
cin>>一个;
printf(A is'%d'\\\
,a);
getline(cin,line);
printf(Line is'%s'\\\
,line.c_str());
cout<< cin.fail()< cin.eof() cin.bad()< endl
}
我也有一个使用istream :: getline写的版本。我相信在这里给出的所有输入案例中的结果是一样的。
a.out< test1
A是'1'
'ine是'abc 2
000
a.out< test2
A是'1'
线是'abc 2'
000
$ b b
其中test1是 $'1 abc 2 \r\\\
(9个字节),test2是
' $'1 abc 2 \ n'
我没有在Windows下明确地做这些测试,
我的问题是:解释测试1的输出。
例如:为什么是printf输出腐败;是否存在与行结束的解释相关的可移植性问题;
在Linux下, getline
从输入流中删除 \\\
。但是,它不会删除
\r
。
回车 \r
)返回将光标移动到当前行的开头。因此在 printf
调用中,当STDOUT游标看到 \r
。它打印的下一个字符是'
,它覆盖行上的第一个字符( L
p>
当文件中没有 \r
时,您不会看到此行为。
轻松解决此问题:在Linux和Unix下运行时手动检查 \r
。
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.
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.
这篇关于在Linux和Windows下混合cin和getline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!