其中C ++编译器是Cygwin和gcc版本8.3.0
以下代码
#include <iostream>
using namespace std;
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
cout << "START" << endl;
int x;
string a, b;
getline(cin, a);
cin >> x; cin.ignore();
getline(cin, b);
cout << a << endl;
cout << b << endl;
cout << x << endl;
cout << "END" << endl;
从Windows 10 命令提示符 命令:
g++ sol.cpp && a.exe < in.txt
和in.txt是文件:
Lorem Ipsum
5
Hello World
打印不正确的输出
START
Lorem Ipsum
5
END
而不是正确的输出
START
Lorem Ipsum
Hello World
5
END
而Cygwin终端(bash)中的相同代码与command:
g++.exe sol.cpp && ./a.exe < in.txt
打印正确的输出:
START
Lorem Ipsum
Hello World
5
END
这里可能是什么问题?
感谢您的回复。答案已解决。正如@Johnny Mopp在上面的评论中指出的那样,Windows分别使用\r\n
即回车和换行,而Unix仅使用\n
,因此在Windows中需要写两个cin.ignore()
]或cin.ignore(2, '\n')
,而在Unix中,一个cin.ignore()
就足够了。