![](/img/trans.png)
[英]I keep getting 0's when I run my program even though the “user” inputs numbers || c++ painting job
[英]I keep getting zeros when after my original inputs
所以我用一個沒有限制的輸入創建一個矢量,但是我想要它,以便當用戶想要停止輸入數據時,他們只是輸入一個非數字鍵,然后繼續前進到下一個矢量,它只是第一個,但是反向並乘以向其中添加了8和100,但是當它繼續前進時,它只是添加了一些零作為輸入
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
vector<int> (myVec1)(n);
vector<int> (myVec2)(n);
int i;
int sum;
for(i=0;i<n;++i){
cout<<"please enter an integer ";
cin>>myVec1.at(i);
cout<<endl;
if(cin.fail()){
for(i=0; i<n; i++){
cout<<myVec1.at(i)<<" ";
}
}
}
cout<<endl;
for(i=0; i<n; i++){
sum=(myVec1.back()*8)+100;
myVec1.pop_back();
cout<<sum<<" ";
}
return 0;
}
這是結果,如您所見,如果有任何人可以幫助我,那么我嘗試停止輸入后只會出現一堆零。id真的很感激:)
請輸入整數435
請輸入整數412
請輸入整數43
請輸入整數56
請輸入整數2
請輸入整數q
435 412 43 56 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100100100100100100100100100100100100100116548 444 3396 3580
int n
具有未定義的值(未初始化)
而是忽略定義n
並像這樣初始化向量: vector<int> myVec1;
讀取值時,請使用myVec1.push_back(valueFromKeyboard);
將其附加到向量中myVec1.push_back(valueFromKeyboard);
#include <iostream>
#include <vector>
using namespace std;
int main () {
vector<int> myVec1;
vector<int> myVec2;
int valueFromKeyboard;
cout << "please enter an integer ";
while (cin >> valueFromKeyboard) {
if (!cin.fail()) {
myVec1.push_back(valueFromKeyboard);
}
cout << "please enter an integer ";
}
for (int i = 0; i < myVec1.size(); i++) {
cout << myVec1[i] << " ";
}
cout << endl << endl;
for (int i = 1; i < myVec1.size()+1; i++) {
myVec2.push_back(myVec1.end()[-i]*8+100);
}
for (int i = 0; i < myVec2.size(); i++) {
cout << myVec2[i] << " ";
}
return 0;
}
myVec1.end()[-1]
是向量的最后一個元素, myVec1.end()[-2]
是倒數第二個, myVec1.end()[-2]
。這就是為什么我for (int i = 1; i < myVec1.size()+1; i++)
從1
轉到myVec1.size()+1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.