为什么这个 while 循环输出非常奇怪的东西
Why does this while loop output very strange things?
我创建了一些代码,要求您输入变量量,然后要求您输入每个变量,然后将其存储在向量中。我遇到的问题是,当您输入不正确的内容时,它会要求您重试,它要么要求您输入变量一定次数,具体取决于您输入的字符,这真的很奇怪。我以为使用ssinput.clear();
可以解决这个问题,但事实并非如此。
例如,如果我在下面的终端中输入这些内容:
Please input variable 1: a
ERROR, PLEASE ENTER ONLY VALID SYMBOLS
---------------------
Please input variable 1: 1
Please input variable 1: 3
Please input variable 1: 5
Please input variable 2: 1
Please input variable 3: 4
Please input variable 4: 3
Please input variable 5: 3
总的来说,它非常零星和奇怪。我的代码在下面。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int inputErrorMessage(){
cout << "n ERROR, PLEASE ENTER ONLY VALID SYMBOLS n";
cout << "--------------------- n";
return 0;
}
int main(){
// Declare the variables, vectors, etc.
int varNum = 1;
int totVar = 5;
vector<double> userNums;
double input = 0;
string checkInput = "";
bool valid = false;
stringstream sstotVar;
while(!valid){
valid = true;
// Ask the user for each variable, then record it into the array
for (int i = 0; i < totVar; ++i) {
cout << "Please input variable " << varNum << ": ";
getline(cin, checkInput);
stringstream ssinput(checkInput);
ssinput >> input;
if (ssinput.fail()) {
inputErrorMessage();
valid = false;
}
if (valid == true) {
userNums.push_back(input);
varNum++;
}
ssinput.clear();
}
}
}
问题出在这些陈述中
vector <double> userNums;
double input = 0;
。
ssinput >> input;
if (ssinput.fail())
检查输入是否包含十进制数字。 这是您不能输入字符的方式。
看看这个。 编译并运行...
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
void inputErrorMessage(){
cout << "n ERROR, PLEASE ENTER ONLY VALID SYMBOLS n";
cout << "--------------------- n";
}
int main(void) {
// Declare the variables, vectors, etc.
int varNum = 1;
int totVar = 5;
vector<string> userNums;
string input = "";
string checkInput = "";
bool valid = false;
stringstream sstotVar;
while(!valid){
valid = true;
// Ask the user for each variable, then record it into the array
for (int i = 0; i < totVar; ++i) {
cout << "Please input variable " << varNum << ": ";
getline(cin, checkInput);
stringstream ssinput(checkInput);
ssinput >> input;
if (ssinput.fail()) {
inputErrorMessage();
valid = false;
}
if (valid == true) {
userNums.push_back(input);
varNum++;
}
ssinput.clear();
}
}
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 我从int x[3]得到的一个非常奇怪的输出;
- 为什么这个 while 循环输出非常奇怪的东西
- 在输出时,我对如何将数量和单词组合在一行感到非常困惑
- Rand() 返回相同或非常相似的输出值
- 音频输出单元启动非常慢
- LLVM Clang在OS X上产生非常慢的输入/输出
- 非常基本的c++程序中的意外输出
- 输出文件中显示的数字非常大