读取以空格分隔的输入数字 [英] Read input numbers separated by spaces

查看:135
本文介绍了读取以空格分隔的输入数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

This may be a total beginner's question, but I have yet to find an answer that works for me.

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

Currently, I'm writing a program for a class that takes in a user's input (which can be one or more numbers separated by spaces), then determines whether the number is prime, perfect, or neither. If the number is perfect, then it will display the divisors.

到目前为止,我已经编写了素数,完美的代码,并列出了除数。我坚持我的程序的输入部分。

Thus far, I've already written the code for the prime, perfect, and listing the divisors. I'm stuck on the input portion of my program. I don't know how to get the input that's separated by spaces to go through my loops one at a time.

这是我当前的程序:

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;

它可以工作,但只能使用一个数字。如果任何人可以帮助我得到它能够读取由空格分隔的多个输入,这将是非常感谢。此外,只是一个旁注,我不知道将输入多少数字,所以我不能只为每个变量。

It works, but only for a single number. If anyone could help me to get it to be able to read multiple inputs separated by spaces, it'd be greatly appreciated. Also, just a side note, I do not know how many numbers will be entered, so I can't just make a variable for each one. It will be a random amount of numbers.

谢谢!

推荐答案

默认情况下, cin 从输入中读取,放弃任何空格。所以,你所要做的就是使用一个do ,而循环多次读取输入:

By default, cin reads from the input discarding any spaces. So, all you have to do is to use a do while loop to read the input more than one time:

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

这篇关于读取以空格分隔的输入数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆