下面的程序没有像Linux G++或freopen()语句中那样接受输入.为什么

this following program not taking input as it should in linux g++ or with freopen() statement...why?

本文关键字:语句 为什么 输入 freopen 程序 G++ Linux      更新时间:2023-10-16

它与使用 stdin 和 stdout 的代码块一起工作得很好,但是当我使用 freopen 重定向流或使用"g++"在 Linux 中运行代码时,输入/输出显示不稳定的行为!!任何人都可以告诉我可能出现的问题。

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,string> p;
int main()
{
// freopen("11.txt","r+",stdin);
// freopen("out.txt","w",stdout);
 int n,t,i,j,k;
string tmp;
cin>>t;
for(i=1;i<=t;i++)
{
    cin>>n;
    fflush(stdin);
priority_queue<p,vector<p>,less<p> > s;
    for(j=0;j<n;j++)
    { getline(cin,tmp);
        map<char,int> mp;
        int c=0;
        for(k=0;k<tmp.length();k++)
        {
            if(tmp[k]!=' '){
            if(mp.find(tmp[k])==mp.end())
            {c++;
              mp[tmp[k]]++;
            }
        }
        }
        if(!s.empty()&&s.top().first<c)
                { s.pop();}
                    s.push(make_pair(c,tmp));
    }
     p ans;
 if(!s.empty())
   ans =s.top();
   string qwe = ans.second;
  cout<<"Case #"<<i<<": "<<qwe<<endl;
  fflush(stdin);
}
return 0;
 }
cin>>n;

其次

getline(cin,tmp);

不起作用,因为第一行通常会在输入流中留下换行符。

添加一行代码以忽略输入流中的其余行。

cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');

紧接着

cin >> n;

确保添加

#include <limits>

使用std::numeric_limits .