【问题标题】:I can't figure it out why this happen in my C++ code我无法弄清楚为什么会在我的 C++ 代码中发生这种情况
【发布时间】:2020-12-19 04:29:31
【问题描述】:

我首先读取一些 int 数并将其存储在一个名为 my 的向量中,然后我尝试先对 size 数求和。这是我完成的代码:

vector<int>my;
cout << "please enter num:" << endl;
int item;
while(cin>>item){
    my.push_back(item);
}
cout << endl;
for(auto i:my){
    cout << i << " ";
}
    
cout << "\nplease enter the num you want to sum: " << endl;
int size;
cin >> size;
    
vector<int>myvector;
for(int i=0;i<size;++i){
    myvector.push_back(my[i]);
}
    
cout << "\nthe nums are: ";
int total{0};
for(auto t:myvector){
    cout << t << " ";
    total += t;
}
cout << "\nthe total is: " << total << endl;

结果:

please enter num:
3
1
2
3
4
5
]

3 1 2 3 4 5 
please enter the num you want to sum: 

the nums are: 
the total is: 0

如您所见,从第二个提示开始,代码无法正常工作,没有给我预期的结果,所以我只是将第二个提示移到顶部,然后它就可以工作了;

cout << "\nplease enter the num you want to sum: " << endl;
int size;
cin >> size;
    
vector<int>my;
cout << "please enter num:" << endl;
int item;
while(cin>>item){
    my.push_back(item);
}
cout << endl;
for(auto i:my){
    cout << i << " ";
}
    
    
vector<int>myvector;
for(int i=0;i<size;++i){
    myvector.push_back(my[i]);
}
    
cout << "\nthe nums are: ";
int total{0};
for(auto t:myvector){
    cout << t << " ";
    total += t;
}
cout << "\nthe total is: " << total << endl;
please enter the num you want to sum: 
3
please enter num:
1
2
3
4
5
]

1 2 3 4 5 
the nums are: 1 2 3 
the total is: 6

有什么想法吗?

【问题讨论】:

  • while(cin&gt;&gt;item){ 将继续从cin 读取,直到流关闭。你确定这是你想要的吗?
  • @scohe001 看来 OP 正试图通过输入] 来“停止” cin,不幸的是,这也是他们的程序无法运行的原因
  • OT,但myvector 是干什么用的?为什么它必须是与my 不同的对象?为什么不能将其初始化为vector&lt;int&gt;myvector = my;?另外,如果sizemy 中的实际元素数量不同会怎样?
  • 提供非整数输入将设置流的失败状态。只要流处于失败状态,就不能使用它来读取任何输入。您必须clear 州。
  • 知道了。非常感谢你们,很酷。

标签: c++


【解决方案1】:

正如 cmets 中所指出的,您的 while (std::cin &gt;&gt; item) 一直读取直到流 std::cin 变为失败状态,例如,当输入非数字时(更准确地说,std::ios_base::failbit 设置为流的状态,即, std::cin.fail() 将返回 true)。它将保持该状态,直到流状态被清除。也就是说,你可以使用

while (std::cin >> item) {
    my.push_back(item);
}

std::cin.clear();  // clear the failure state of the stream
std::cin.ignore(); // ignore the next character

int size;
if (!(std::cin >> size)) {
    std::cout << "failed to read an integer from standard input\n";
    // do some error recovery, e.g., bail out of the program
}
// carry on with your processing

就个人而言,我倾向于将std::cin 中的数据直接读取到向量中,例如,使用

std::vector<int> my{std::istream_iterator<int>(std::cin),
                    std::istream_iterator<int>()};

当然,流仍然需要clear()ed 和分隔符ignore()ed。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2013-11-21
    相关资源
    最近更新 更多