如何在C 行中丢弃额外的输入

How to discard extra inputs in a line c++

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

我是C 的新手。我正在尝试从用户那里获得输入,以插入多维向量。该代码正常运行。但是,当我在同一行中提供额外的输入时,我的程序不会忽略它,并在下一个迭代中考虑它。

例如,当我以以下格式给出输入时:

m=3 n=4
1 2 3 4 5
1 3 5 5
1 345 65 567

输出为

1   2   3   4
5   1   3   5
5   1 345  65

但是我想要的输出是

1   2   3   4
1   3   5   5
1   345 67  567
int main() {
    vector<vector<int>> vec;
    int m, n, dat;
    cout << "Enter dimensions of Vector";
    cin >> m >> n;
    // takes data n times into a subvector temp and inserts it into the vector vec m
    // times
    cout << "Enter elements one row at a time";
    for(int i = 0; i < m; ++i) {
        vector<int> temp;
        for(int j = 0; j < n; ++j) {
            cin >> dat;
            temp.push_back(dat);
        }
        vec.push_back(temp);
    }
    for(int k = 0; k < vec.size(); ++k) {
        for(int i = 0; i < vec[k].size(); ++i) {
            cout << setw(4) << vec[k][i];
        }
        cout << endl;
    }
}

考虑使用std::getline读取完整的行。然后,您可以使用它来填充std::istringstream,然后用它来提取所需的元素数量。另请注意:

为什么"使用命名空间std";被认为是不良习惯吗?

示例:

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main() {
    std::vector<std::vector<int>> vec;
    int m, n, dat;
    std::cout << "Enter dimensions of Vector";
    std::cin >> m >> n;
    std::cin.ignore(); // skip newline
    // takes data n times into a subvector temp and inserts it into the vector vec m
    // times
    std::cout << "Enter elements one row at a timen";
    for(int i = 0; i < m; ++i) {
        std::string line;
        std::vector<int> temp;
        std::cout << " row " << (i + 1) << ": ";
        std::getline(std::cin, line);
        std::istringstream iss(line);
        for(int j = 0; j < n; ++j) {
            iss >> dat;
            temp.push_back(dat);
        }
        vec.push_back(temp);
    }
    for(const auto& row : vec) {
        for(int colval : row) {
            std::cout << std::setw(4) << colval;
        }
        std::cout << "n";
    }
}