读取以空格分隔的输入数字

新手上路,请多包涵

这可能是一个完全初学者的问题,但我还没有找到适合我的答案。

目前,我正在为一个接收用户输入(可以是一个或多个用空格分隔的数字)的类编写程序,然后确定该数字是质数、完美数还是两者都不是。如果数字是完美的,那么它将显示除数。

到目前为止,我已经编写了素数、完美数和除数列表的代码。我被困在程序的输入部分。我不知道如何让用空格分隔的输入一次通过我的循环。

这是我目前的程序:

 cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
cin>>num;

while (divisor<=num)
    if(num%divisor==0)
    {
        cout<<divisor<<endl;
        total=total+divisor;
        divisor++;
    }
    else divisor++;
if(total==num*2)
    cout<<"The number you entered is perfect!"<<endl;
else cout<<"The number you entered is not perfect!"<<endl;

if(num==2||num==3||num==5||num==7)
    cout<<"The number you entered is prime!"<<endl;

else if(num%2==0||num%3==0||num%5==0||num%7==0)
    cout<<"The number you entered is not prime!"<<endl;
else cout<<"The number you entered is prime!"<<endl;

return 0;

它有效,但仅适用于单个数字。如果有人可以帮助我让它能够读取由空格分隔的多个输入,将不胜感激。另外,顺便说一句,我不知道要输入多少个数字,所以我不能只为每个数字做一个变量。这将是随机数量的数字。

谢谢!

原文由 Raymond Aaron 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

默认情况下, cin 从输入中读取并丢弃任何空格。因此,您所要做的就是使用 do while 循环多次读取输入:

 do {
   cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
   cin >> num;

   // reset your variables

   // your function stuff (calculations)
}
while (true); // or some condition

原文由 Murilo Vasconcelos 发布,翻译遵循 CC BY-SA 3.0 许可协议

你会想要:

  • 从控制台读入整行
  • 标记线,沿空格分开。
  • 将这些拆分的部分放入数组或列表中
  • 遍历该数组/列表,执行您的主要/完美/等测试。

到目前为止,您的课程涵盖了哪些内容?

原文由 ravuya 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题