Reading three inputs from the user using Console.ReadLine()

萝らか妹 提交于 2020-01-05 08:43:57

问题


Is this the correct way to do it, since I'm new to C#

Console.WriteLine("please enter m,y,n: \n");
double month, year, numberOfMonths = Convert.ToDouble(Console.ReadLine());

回答1:


You can do it by asking user to enter the values split-ed by some delimiter like space, semi colon etc. And then split the value and parse accordingly. for example

string input = Console.ReadLine();
string[] split = input.Split(',');
double month = Double.Parse(split[0]);
double year = Double.Parse(split[1]);
double numberofmonth = Double.Parse(split[2]);

Ofcourse the above code is not the most elegant/efficient/error free code. But, it is just written to get the idea across.




回答2:


try this:

     double month;
     double year;
     double numberOfMonths;
     Console.WriteLine("please enter m \n");
     month=Convert.ToDouble(Console.ReadLine());
     Console.WriteLine("please enter y \n");
     year=Convert.ToDouble(Console.ReadLine());
     Console.WriteLine("please enter n \n");
     numberOfMonths=Convert.ToDouble(Console.ReadLine());



回答3:


You can also store input in an array and tell the user to press enter after every input and then doing this:

string[] input=new string[3];
Console.WriteLine("please enter m,y,n: \n");
for(int i=0;i<3;i++)
  input[i]=Console.ReadLine();

then you can convert the string input to whatever datatype you want, the above is not a very efficient way, but you can use it to get large number of input from user and its easy when all the input have the same datatype.



来源:https://stackoverflow.com/questions/21619573/reading-three-inputs-from-the-user-using-console-readline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!