简体   繁体   中英

How to read input from a C++ file with K lines of input and N elements on each line from stdin

I am just learning C++ and I want to read input from the file "gymnastics.in" with K lines of input, and N integers on each line, N is the same for all the integers. The input would look something like this:

3 4
4 1 2 3
4 1 3 2
4 2 1 3

The first line containing K, and N respectively. And then three lines after that with four elements each. I have tried making a vector of vectors (nested vector?). This is what I have:

ifstream fin("gymnastics.in");
ofstream fout("gymnastics.out");
int k, n;
fin >> k >> n;
vector<vector<int> > nums;
for (int i = 0; i < k; i++) {
    vector<int> temp_nums;
    for (int j = 0; j < n; j++) {

    }
}

I have tried to make a temporary list to then push back to the bigger nums. But now I am stuck here, because I can only use this way if I have a definite number for N (ie 1, 2, 5, 10) so then I could create variables for each of it and add them to the temp_nums then add it to nums. but because I don't have a definite number for N (could be 1, 2, or 100) I don't know what to do. Any help would be appreciated, thank you.

You're almost there. All you have to do in your inner for loop is extract your number from the stream and add it to your temp vector. Then you can add the temp_vector to nums .

Since you know it's always an integer, you could declare say an int temp_val variable and read all n numbers on a line one at a time. Then use vector::push_back to add each number to your temp vector. It would look something like this:

int temp_val;

for (int i = 0; i < k; ++i) {

    vector<int> temp_nums;
    // Alternate: vector<int> temp_nums(k);  

    for (int j = 0; j < n; j++) {

        fin >> temp_val;

        temp_nums.push_back(temp_val);
        // Alternate: temp_nums.at(j) = temp_val;

    }
 
    nums.push_back(temp_nums);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM