您好,这可能是由于您对函数作用的错误理解所致。 `fflush` 并不具备“处理换行符”的作用。
by only_a_speaker @ 2023-10-24 14:12:32
@[only_a_speaker](/user/1154375)
fflush不是可以清空缓冲区内容嘛?输入n后回车,然后我为了让之后的getchar不读入缓冲区的换行符,就想用fflush清空缓冲区。
------------
本地跑的情况是:fflush和两次getchar等效,都可以过数据点1;但是洛谷评测中用fflush并没能达到清空缓冲区的效果,使得数据点1不通过
by Selvare @ 2023-10-24 18:46:02
@[only_a_speaker](/user/1154375)
这是ac代码
```cpp
#include<iostream>
#include<cstring>
using namespace std;
const char c[] = {'\0', '\n'};
const int fx[] = {-1, 0, 1, 0},
fy[] = {0, 1, 0, -1};
int n, tot, mmap[500][500];
void dfs(int x, int y)
{
mmap[x][y] = 0;
int nx, ny;
for(int i = 0; i < 4; ++ i)
{
nx = x+fx[i], ny = y+fy[i];
if(nx == 0 || nx == n+1 || ny == 0 || mmap[nx][ny] == -1 || mmap[nx][ny] == 0) continue;
//cout << nx <<" "<< ny << endl;
dfs(nx, ny);
}
return;
}
int main()
{
cin >> n;
//fflush(stdin);
getchar(); getchar();
for(int i = 1; i <= n; ++i)
{
char ch;
int cnt = 1;
while((ch = getchar()) != '\n')
{
if(ch >= 'a' && ch <= 'z') mmap[i][cnt] = 1;
if(isprint(ch)) cnt++;
}
mmap[i][cnt] = -1;
}
/*for(int i = 1; i <= n; ++i)
for(int j = 1; mmap[i][j-1] != -1; ++j)
cout << mmap[i][j] << c[mmap[i][j] == -1];*/
for(int i = 1; i <= n; ++i)
for(int j = 1; mmap[i][j] != -1; ++j)
if(mmap[i][j]) dfs(i, j), tot++;
/*puts("");
for(int i = 1; i <= n; ++i)
for(int j = 1; mmap[i][j] != -1; ++j)
cout << mmap[i][j] << c[mmap[i][j+1] == -1];*/
cout << tot;
return 0;
}
``````
by Selvare @ 2023-10-24 18:53:20
@[Selvare](/user/386852)
您好,你可能是用控制台进行程序的运行测试,然而使用文件进行运行测试才是合理的。
即便你在控制台测试出了“fflush吞掉了换行字符”的现象,你由此得出的结论也是不合理的。不妨进行如下测试:
```cpp
#include<iostream>
using namespace std;
int main()
{
cout<<int(getchar())<<'\n';
cout<<int(getchar())<<'\n';
cout<<int(getchar())<<'\n';
fflush(stdin);
cout<<int(getchar())<<'\n';
cout<<int(getchar())<<'\n';
cout<<int(getchar())<<'\n';
}
```
你可以输入 `12345` 换行之后再输入 `123` 。你会发现 `45` 都被吞掉了,所以 `fflush` 跟“处理换行”没关系,最好以文件进行输入以模拟 `oj` 。
by only_a_speaker @ 2023-10-24 19:07:01