C++ 为什么cin不在for循环内部执行? #包括 #包括 使用名称空间std; 类型定义向量向量向量//vec现在起着数据类型的作用 int main() { vec powers;//在目标函数中存储x的幂 向量系数;//在目标函数中存储x的系数 双倍功率; 双系数=0; cout
这里的问题是你告诉用户输入一个字符结束C++ 为什么cin不在for循环内部执行? #包括 #包括 使用名称空间std; 类型定义向量向量向量//vec现在起着数据类型的作用 int main() { vec powers;//在目标函数中存储x的幂 向量系数;//在目标函数中存储x的系数 双倍功率; 双系数=0; cout,c++,for-loop,cin,C++,For Loop,Cin,这里的问题是你告诉用户输入一个字符结束 #include <iostream> #include <vector> using namespace std; typedef vector<double> vec; //vec now acts like a datatype int main() { vec powers; //stores powers
#include <iostream>
#include <vector>
using namespace std;
typedef vector<double> vec; //vec now acts like a datatype
int main()
{
vec powers; //stores powers of x in the objective function
vec coefficients; //stores coefficients of x in the objective function
double pow;
double coeff = 0;
cout << "Enter powers of x present in the objective function and enter any character to stop" << endl;
cout << "REMEMBER TO ENTER 0 IF CONSTANT EXISTS!" << endl;
while (cin >> pow)
powers.push_back(pow); //Working fine
cout << endl;
for (vec::iterator iter_p = powers.begin(); iter_p != powers.end(); iter_p++)
{
double coeff;
cout << "Enter coefficient of the (x^" << *iter_p << ") term: ";
cin >> coeff; //THIS IS NOT EXECUTING
coefficients.push_back(coeff); //NOT WORKING EITHER
}
cout << endl;
return 0;
system("pause");
}
这样做的同时,它也会将cin
置于错误状态,并将字符保留在缓冲区中。您需要清除该错误状态并清除输入中留下的字符。您可以通过添加
while (cin >> pow)
powers.push_back(pow);
cin.clear();
cin.ignore(std::numeric_limits::max(),'\n');
在while循环之后。
clear
清除错误,调用ignore将清除输入中留下的任何字符。这里的问题是告诉用户输入一个字符结束
#include <iostream>
#include <vector>
using namespace std;
typedef vector<double> vec; //vec now acts like a datatype
int main()
{
vec powers; //stores powers of x in the objective function
vec coefficients; //stores coefficients of x in the objective function
double pow;
double coeff = 0;
cout << "Enter powers of x present in the objective function and enter any character to stop" << endl;
cout << "REMEMBER TO ENTER 0 IF CONSTANT EXISTS!" << endl;
while (cin >> pow)
powers.push_back(pow); //Working fine
cout << endl;
for (vec::iterator iter_p = powers.begin(); iter_p != powers.end(); iter_p++)
{
double coeff;
cout << "Enter coefficient of the (x^" << *iter_p << ") term: ";
cin >> coeff; //THIS IS NOT EXECUTING
coefficients.push_back(coeff); //NOT WORKING EITHER
}
cout << endl;
return 0;
system("pause");
}
这样做的同时,它也会将cin
置于错误状态,并将字符保留在缓冲区中。您需要清除该错误状态并清除输入中留下的字符。您可以通过添加
while (cin >> pow)
powers.push_back(pow);
cin.clear();
cin.ignore(std::numeric_limits::max(),'\n');
在while循环之后。
clear
清除错误,调用ignore将清除输入中留下的任何字符。也许您应该刷新流…即cout@Emil推std::endl
或从std::cin
读取。也许您应该刷新流…即cout
@Emil按下std::endl
或从std::cin
读取两个刷新std::cout
。