簡體   English   中英

我無法弄清楚為什么在我的 C++ 代碼中會發生這種情況

[英]I can't figure it out why this happen in my C++ code

我首先在一個名為my的向量中讀取並存儲了一些 int 數字,然后我嘗試對第一個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 (std::cin >> item)會一直讀取,直到 stream std::cin變成失敗 state,例如,當輸入非數字時(更准確地說, std::ios_base::failbit在流的 state 上設置,即std::cin.fail()將返回true )。 它將保留在 state 中,直到 stream state 被清除。 也就是說,您可以使用

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>()};

當然, stream 仍然需要clear() ed 和分隔字符ignore() ed。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM