如何从文件循环中获取多行?

时间:2018-03-23 06:21:58

标签: c++

我希望从文件中顺序获取多行,然后将它们保存到变量中。如果在Java中可以使用scanner.nextInt

C ++怎么样?

int main(){
        string line;
        int a, b, c;
        ifstream myFile("input.in");
        if(myFile.is_open()){
            while(getline(myFile,line)){
                int cases = atoi(line.c_str());
                double count[cases];
                cout << "cases : "<<cases << "\n";
                for(int i = 1; i <= cases; i++){
                    a = atoi(line.c_str());
                    b = atoi(line.c_str());
                    c = atoi(line.c_str());
                    cout << a << b << c;
                }
            }
        }        
        return 0;
    }

1 个答案:

答案 0 :(得分:0)

您可以使用while(input.in >> cases)将下一个int读入cases,直到达到文件结尾(EOF)。我已在下面更新了您的代码。

int main(){
    string line;
    int a, b, c;
    ifstream myFile("input.in");
    if(myFile.is_open()) {
        int cases = 0;
        while(myFile >> cases) { // breaks on eof
            double count[cases];
            cout << "cases : " << cases << "\n";
            for(int i = 1; i <= cases; i++){
                myFile >> a;
                myFile >> b;
                myFile >> c;
                cout << a << b << c;
            }
        }
    }        
    return 0;
}