我正在制作一个C ++程序来处理书籍。用户需要插入3本书的标题,价格和数量。我没有在代码中包含Book
类,因为它与我的问题无关。
我被困在用户需要在循环内输入值的位置。当我测试程序时,控制台在看似随机的时间里保持窃听。 (即它显示"Give book p"
而不是完整的句子,等待输入。)
我在其他答案中读到我应该在每次cin.ignore()
调用后使用cin>>
,以便忽略当用户按Enter键时放在流上的\n
,但它没有& #39;解决我的问题?
任何想法我做错了什么?
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string title;
double price;
int volumes;
for (int i=0; i<3;i++){
cout << "Give book title : " << endl;
getline (cin, title);
cout << "Give book price : " << endl;
cin >> price;
cin.ignore();
cout << "Give number of volumes : " << endl;
cin >> volumes;
cin.ignore();
}
return 0;
}
以下是控制台的示例:
Give book title : The Hobbit The Hobbit Give book price : 12.5 12.5 Give number of volumes : 10 10 Give book title : Lord of the Rings Lord of the Rings Give book price : 12 12 Give number of volumes : 7 7 Give bo
正如你所看到的那样,最后一句被切掉了,控制台被卡住了。
答案 0 :(得分:0)
您可以使用# Library
library(MASS)
library(boot)
# Get data
data(iris)
names(iris) <- gsub("\\.", "", names(iris)) #remove dots from column names
# Split data into train and test sets
train_index <-sample(seq(nrow(iris)),floor(dim(iris)[1]*0.75))
train <- iris[train_index,]
test <- iris[-train_index,]
test_Y <- test[, c('Species')]
test_X <- subset(test, select=-c(Species))
#### LDA without bootstrap:
# Fit LDA to train data:
lda.fit = lda(Species ~ . , data=train)
lda.fit
# Predict test_Y based on lda.fit above
lda.pred <- predict(lda.fit, test_X)
lda.class <- lda.pred$class
# Confusion matrix
table(lda.class, test_Y)
#### LDA with bootstrap:
# Fit LDA to train data: to get standard errors for coefficients
set.seed(1)
boot.fn <- function(data,index){
return(coefficients(lda(Species ~ SepalLength + SepalWidth + PetalLength + PetalWidth, data=data, subset=index)))
}
# Call boot(): This returns LD1 and LD2 for each predictor
boot(train, boot.fn, 1000)
# NOTE: Here, in Bootstrap Statistics output, t1* to t4* are LD1 coefficients and t5* to t8* are LD2 coefficients
作为std::ws
方法的参数来实现目标。
以下代码将满足您的目的:
getline()
这将产生以下输出:
#include <iostream>
int main() {
std::string title;
double price;
int volumes;
for (int i=0; i<3;i++){
std::cout << "Give book title : ";
std::getline(std::cin >> std::ws, title);
std::cout << "Give book price : ";
std::cin >> price;
std::cout << "Give number of volumes : ";
std::cin >> volumes;
std::cout<<"Title: "<<title<<" costs "<<price<<" for "<<volumes<<" volumes.\n";
}
return 0;
}