关于 getline 和 getchar
  • 板块学术版
  • 楼主ZZQF5677
  • 当前回复7
  • 已保存回复7
  • 发布时间2023/8/23 17:46
  • 上次更新2023/11/3 01:42:28
查看原帖
关于 getline 和 getchar
482347
ZZQF5677楼主2023/8/23 17:46

有时出现以下情况要整行读入时,需要用 getline⁡(cin⁡,s)\operatorname{getline}(\operatorname{cin}, s)。但是必定会读入那个整数的换行符。

20
abcde 114514 1919810

一般换行符用 getline⁡(cin⁡,nothing)\operatorname{getline}(\operatorname{cin}, nothing) 读取,也可以用 getchar⁡()\operatorname{getchar}() 读取。

但是为什么会出现 getline⁡(cin⁡,nothing)\operatorname{getline}(\operatorname{cin}, nothing) 可读入 windows 或者 linux 的换行,而 getchar⁡()\operatorname{getchar}() 仅仅只读入 linux 的换行符。(弄得我把老师造的数据传到洛谷上时提交全 WA 了。)

个人初步认为是 getline⁡(cin⁡,nothing)\operatorname{getline}(\operatorname{cin}, nothing) 读入整行,读入 \n 或者 \r\n。而 getchar⁡()\operatorname{getchar}() 在以上情况中读入单个字符 \n 或者 \r 就跑路了。虽然 CCF 是 linux 系统,此情况下 getline⁡(cin⁡,nothing)\operatorname{getline}(\operatorname{cin}, nothing) 或者 getchar⁡()\operatorname{getchar}() 读换行符皆可。()()()

情况可以参考本题()

https://www.luogu.com.cn/problem/U331543

#1 为 Unix(LF)

#2 为 CRLF。

#include <bits/stdc++.h>
using namespace std;
int n;
string s;
string nothing;
int main() {
  cin >> n;
  getchar();
  getline(cin, s);
  cout << s;
  return 0;
}

50pts

#include <bits/stdc++.h>
using namespace std;
int n;
string s;
string nothing;
int main() {
  cin >> n;
  getchar();
  getline(cin, s);
  cout << s;
  return 0;
}

100pts

求问原因()()()

2023/8/23 17:46
加载中...