C++输入困难

C++ input difficulty

本文关键字:输入 C++      更新时间:2023-10-16

我正在尝试解决ACM Timus的以下问题:http://acm.timus.ru/problem.aspx?space=1&num=1242,但我不知道如何正确读取输入。我正在使用两个while循环。一旦在输入中写入字符串,第一个就会终止,但第二个之后就不起作用了。这是我的代码:

#include <iostream>
#include <vector>
using namespace std;

struct Pair
{  
    void AddParent(int a)
    { parents.push_back(a); }
    void AddChild(int a)
    { children.push_back(a);}
    vector<int> parents;
    vector<int> children;
};
vector<bool> visited;
vector<Pair> graph;
void DFS1(int n)
{
    visited[n] = true;
    for(int i = 0 ; i < graph[n].parents.size() ; i++)
    {
        int t = graph[n].parents[i];
        if(!visited[t])
            DFS1(t);
    }
    return;
}
void DFS2(int n)
{
    visited[n] = true;
    for(int i = 0 ; i < graph[n].children.size() ; i++)
    {
        int t = graph[n].children[i];
        if(!visited[t])
            DFS2(t);
    }
    return;
}

int main()
{
    int n;
    cin >> n; 
    graph.resize(n);
    visited.resize(n);
    int a,b,c;
    vector<int> victim;
////////////////////////////////
    while(cin >> a && cin >> b)
    {   a--;b--;
        graph[a].AddParent(b);
        graph[b].AddChild(a);
    }
    cin.clear();
    cin.ignore();
    while(cin >> c)
    {
        victim.push_back(c);
    }
////////////////////////////////    
    for(int i = 0 ; i < victim.size() ; i++)
        if(!visited[victim[i]]){
            DFS1(victim[i]);
            DFS2(victim[i]);
        }

    bool vis = false;
    for(int i = 0 ;  i < n ; i++)
        if(!visited[i])
        { 
            vis = true;
            cout << i + 1 << " ";
        }
        if(!vis)
            cout << 0;
return 0;
}

在进入第二个 while 循环之前,您应该清除输入流 cin。

    while(cin >> a && cin >> b)
    {   a--;b--;
        graph[a].AddParent(b);
        graph[b].AddChild(a);
    }
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    while(cin >> c)
    {
        victim.push_back(c);
    }

并包括标头限制

为什么我们在读取输入后调用 cin.clear() 和 cin.ignore()?