我有一個簡單的 C 測驗代碼。它應該作業的方式是讓用戶通過 輸入整數序列cin,然后輸入一些字符來終止cin輸入,然后代碼應該輸出整數。接下來,用戶應該輸入一個非零的整數來輸入另一個序列。如果這是用戶所做的,則該程序再次開始,否則代碼退出。
例如,我期待輸入
1 2 3 4 5 a
導致輸出
1, 2, 3, 4, 5
然后有機會輸入另一個序列的信號。相反,這個輸出會無限重復(或直到 ctrl-c):
1, 2, 3, 4, 5
1, 2, 3, 4, 5
1, 2, 3, 4, 5
etc.
這是怎么回事cin?我知道getline(),并且可能可以用它解決問題。但是,無論如何,我認為我需要了解一些簡單而基本的東西cin。這是代碼:
#include <iostream>
#include <vector>
int main(int argc, char **argv) {
std::vector<int> data;
int goahead = 1;
int nextval;
while (goahead) {
while (std::cin >> nextval) {
data.push_back(nextval);
}
for (int i=0; i<data.size(); i ) {
if (i>0) std::cout <<", ";
std::cout << data[i];
}
std::cout << std::endl;
std::cin >> goahead;
}
}
uj5u.com熱心網友回復:
使用cin.clear()和cin.ignore()可以幫助:
#include <iostream>
#include <vector>
#include <limits>
int main(int argc, char **argv) {
std::vector<int> data;
int goahead = 1;
int nextval;
while (goahead) {
data.clear();
while (std::cin >> nextval) {
data.push_back(nextval);
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for (int i=0; i<data.size(); i ) {
if (i>0) std::cout <<", ";
std::cout << data[i];
}
std::cout << std::endl;
std::cin >> goahead;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
此致。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513842.html
標籤:C 辛考特
下一篇:C 不能只回傳字串的第n個元素
