C++ 如何使用forloop确定已输入的字符数?

C++ 如何使用forloop确定已输入的字符数?,c++,calculator,cin,C++,Calculator,Cin,所以我仍然在用计算器计算代数方程,但我遇到了一点麻烦。我想设置程序,如果你输入超过4个不同的数字,它会在屏幕上打印一个通知,给你第二次机会。但是,我的forloop不起作用。如果输入5个字符,它会询问您要执行的类型(类型表示您想要4个正数4个负数,等等),然后程序会重置。下面是代码的样子(如果需要更多信息,我将根据请求更新线程): else if(type==“foil”) { cout>X1>>X2>>Y1>>Y2; int nCount=0; for(nCount==cin.beg;nCou

所以我仍然在用计算器计算代数方程,但我遇到了一点麻烦。我想设置程序,如果你输入超过4个不同的数字,它会在屏幕上打印一个通知,给你第二次机会。但是,我的forloop不起作用。如果输入5个字符,它会询问您要执行的类型(类型表示您想要4个正数4个负数,等等),然后程序会重置。下面是代码的样子(如果需要更多信息,我将根据请求更新线程):

else if(type==“foil”)
{
cout>X1>>X2>>Y1>>Y2;
int nCount=0;
for(nCount==cin.beg;nCount!=cin.end;nCount++)
{
如果(n计数>4)
{
printf(“请输入4个不同的数字。\n”);
睡眠(1000);
返回main();
}
其他的
{
打破
}
}
//forloop之后是指您有机会输入不同的
//组合箔可以有2个负2个正4个负4个正等。
}

好吧,我想你有几个问题。 首先,循环总是在第一次迭代中中断,因为if语句总是采用else分支。 当进入for循环时,语句
nCount>4
将始终为false

第二个问题是
nCount==cin.beg;n计数!=cin.end;nCount++
我猜提取操作符会从流中删除字节,但找不到任何引用atm。所以你不能确定它的大小

我建议这样做来验证用户输入

char accepted = 'n';
do {
    accepted = 'n'
    cout << "Please input the value of X1, X2, Y1, and Y2 (Example: 8 9 4 9)\n";
    cin >> X1 >> X2 >> Y1 >> Y2;
    cin.clear();

    //Print out values
    cout << "Are those values corrent? y/n"
    cin >> accepted;
    cin.clear();
} while (accepted != 'y');
char接受='n';
做{
已接受='n'
cout>X1>>X2>>Y1>>Y2;
cin.clear();
//打印值
不能接受;
cin.clear();
}while(已接受!=“y”);

我建议您使用
std::vector
来保存变量:

std::vector<int> values(4);
cout << "Please input the value of X1, X2, Y1, and Y2 (Example: 8 9 4 9)\n";
for (unsigned int i = 0;
    (cin.good()) && (i < 4);
    ++i)
{
    cin >> values[i];
}
if (values.size() < 4)
{
  // handle error
}  

我认为所需信息较少。您应该删除与问题无关的所有内容,例如
while(1)
循环、所有
std::cout
输出、
Sleep
调用、
toupper
\u getche
等等……啊,好吧,很抱歉,我只是想确保没有遗漏任何内容。我将继续编辑这些内容。重点是问题不应该包含任何多余的内容,也不应该太短而无法实际展示问题。谢谢你的链接。把它清理干净,只显示初始问题发生的地方。答案很好,但这样做会要求整个程序重写正确吗?特别是箔片程序的一部分,因为它输出这个(以及它的不同变体):cout
std::vector<int> values(4);
cout << "Please input the value of X1, X2, Y1, and Y2 (Example: 8 9 4 9)\n";
for (unsigned int i = 0;
    (cin.good()) && (i < 4);
    ++i)
{
    cin >> values[i];
}
if (values.size() < 4)
{
  // handle error
}  
struct Coordinate
{
  int x;
  int y;
  friend istream& operator>>(istream& inp, Coordinate& p);
};

istream& operator>>(istream& inp, Coordinate& p)
{
  inp >> p.x >> p.y;
  return inp;
}

int main(void)
{
  Coordinate p1;
  Coordinate p2;
  cout << "Please input point 1:";
  if (!(cin >> p1))
  {
    cerr << "Error inputting point 1.\n";
    return EXIT_FAILURE;
  }
  cout << "\nPlease input point 2:";
  if (!(cin >> p2))
  {
    cerr << "Error inputting point 2.\n";
    return EXIT_FAILURE;
  }
  // ...
  return EXIT_SUCCESS;
}