c++ - 该程序不会读取 C++ 中的第二个 vector

标签 c++ vector

所以我尝试编写一个可以返回两个 vector 的标量积的函数(即 a0b0 + a1b1 + ...),但是每当我运行该程序时,它只会读取第一组输入(即 vector a),然后第二个 vector ( vector b)被自动“跳过”,程序返回一个非常奇怪的数字,如 2.122e-314。那么这段代码有什么问题呢? (为简单起见,我假设 vector a 和 b 具有相同的大小。)谢谢!

#include <iostream>
#include <vector>

using namespace std;

/**
 Calculates the scalar product of two vectors.
 @param a, b two vectors
 @return the sum of product of two vectors: a0b0 + a1b1 + ...
 */
double scalar_product (vector<double>& a, vector<double>& b)
{
    double product;
    for (int i = 0; i < a.size(); i++)
        product += a[i] * b[i];
    return product;
}

/**
 Reads in a new vector.
 */
vector<double> read (vector<double>& a)
{
    bool more = true;
    while (more)
    {
        double s;
        cin >> s;
        if (cin.fail())
            more = false;
        else
            a.push_back(s);
    }
    return a;
}

int main()
{
    vector<double> a;
    cout << "Please enter the numbers of the first series, enter any non-number character to quit: ";
    read (a);

    vector<double> b;
    cout << "Please enter the numbers of the second series, enter any non-number character to quit: ";
    read (b);
    cout << "The scalar product of the two series is " << scalar_product(a, b) << "\n";
    return 0;
}

最佳答案

您需要在读取第一个 vector 后调用 cin.clear() 来重置错误标志。正如 Peter 所提到的,您还需要忽略 cin 中的非数字字符。您可以使用 cin.ignore(10000,'\n'); 之类的方法来执行此操作,它将忽略所有字符,直到换行为止。

关于c++ - 该程序不会读取 C++ 中的第二个 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23023101/

相关文章:

c++ - UI 菜单开发资源

c++ - 从右值对象返回一个成员

c++ - 线程安全 vector : Is this implementation thread-safe?

矢量查找的 R 习语

c++ - 初始化 auto-inc 类型 vector 的 vector 时出现问题

C++ DirectX9 不正确的 Sprite 旋转

c++ - gcc 的自动向量化消息是什么意思?

c++ - 如何在 mpi 中发送字符串 vector ?

java - 求凸多边形 vector 交点的度数

c++ - 对象指针 vector 返回奇数