【问题标题】:C++ Input Stream failC++ 输入流失败
【发布时间】:2015-08-11 01:16:22
【问题描述】:

我编写了一个程序,它基本上要求用户输入两个向量整数的元素。然后它比较这个向量,但程序忽略了我的第二个输入流。但是,控制台不会打印错误,它只会跳过第二个输入。

#include <vector>
#include <iostream>

using namespace std;

int main() {
//Introduction
cout << "This is a comparison program between two vectors of ints." << endl;

vector<int> ivec1;
vector<int> ivec2;
//First vector
int v1;
cout << "Insert the values for the first vector." << endl; 
while (cin >> v1) {
    ivec1.push_back(v1);
}
cin.clear();
//Second vector
int v2;
cout << "Insert the values for the second vector." << endl;
while (cin >> v2) {
    ivec2.push_back(v2);
}
cin.clear();
//Equal? If yes, first smaller?
if (ivec1 == ivec2) {
    cout << "Both vectors are equal." << endl;
}
else {
    if (ivec1 < ivec2)
        cout << "This two vectors are unequal and the first vector is smaller." << endl;
    else
        cout << "This two vectors are unequal and the second vector is smaller." << endl;
}
}

【问题讨论】:

  • 您准备好学习如何在调试器中单步调试您的代码了吗?
  • 你继续使用cin.clear()。我不认为它意味着你认为它的意思。
  • @DrewDormann 恐怕 OP 没有丝毫线索。但这将在越来越多的问题中变得普遍。大多数时候我都懒得再问了。只是 DVCV :-P ..
  • @DrewDormann 我是 C++ 新手。我不知道怎么用。
  • @JanGross 使用调试器是掌握一门编程语言最基本的技能之一!大多数 IDE(您可能正在使用一个)只是提供开箱即用的单步执行代码功能。

标签: c++ vector input


【解决方案1】:

从“控制台不打印错误”(假设不打印任何内容)和“跳过第二个输入流”,我想知道您是否正在终止程序而不是提供正确的 EOF 流(通过按 Ctrl + D) 转到第二个输入流。

【讨论】:

  • 我提供EOF。第一个流是好的,但它会跳过第二个输入流并提供第二个向量 0 元素。然后比较说第一个向量更大。
猜你喜欢
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
  • 2013-06-30
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
  • 2019-06-11
  • 2016-02-23
相关资源
最近更新 更多