c# - 如果int变量是一个字符串,如何读取它

时间:2017-06-16 00:08:27

标签: c#

我刚刚在一个测试中遇到这个,如果输入无效则结束循环然后结束程序。我的代码就像这样

    int x=0;
    while(x!=(string)) // this is what I want to know what should i do here
  {
    Console.WriteLine("Input an integer: ");
    x = Int.Parse(Console.ReadLine);
  }
    Console.WriteLine("Invalid input");

这样做的正确方法是什么?
附:那个时候,我还不知道int.TryParse。所以,我正在寻找一种不使用int.TryParse

的方法

4 个答案:

答案 0 :(得分:2)

对我来说,这听起来像是一个带有int.tryparse的do-while循环的作业。

一个简单的代码示例如下:

        string input = string.Empty;

        int x = 0;
        do
        {
            input = Console.ReadLine();
        } while (int.TryParse(input, out x));

        Console.WriteLine("Invalid entry");

        Console.ReadKey();

Do while的工作方式类似于while循环,但它将条件结束,最后允许使用tryparse。

当值可以成功解析为整数时,Tryparse返回布尔值true,否则返回false并结束循环。

答案 1 :(得分:2)

如果你只想读取一个字符串,尝试转换为一个整数,如果它不是一个有效的整数,则退出程序,然后你使用int.TryParse,如下所示:

string input = Console.ReadLine();
if (int.TryParse(input, out x))
{
    // do something with x
}
else
{
    // input was invalid.
}

如果你想在循环中继续这样做,直到输入无效:

bool validInput = true;
while (validInput == true)
{
    string input = Console.ReadLine();
    int x;
    if (int.TryParse(input, out x))
    {
        Console.WriteLine(x);  // output the integer
    }
    else
    {
        Console.WriteLine("Input was not an integer");
        validInput = false;
    }
}

更新

您的测试究竟是什么意思是“整数?”它只是一个字符串,只包含集合[0-9]中的一个或多个数字?或者它是否需要符合C#语言对Int32的定义?如果是前者,则可以使用正则表达式来确定字符串是否只是数字。否则,int.TryParseint.Parse包含在try ... catch中就是您必须这样做的方式。

答案 2 :(得分:1)

试试这个:

         Console.WriteLine("About to call Console.ReadLine in a loop.");
        Console.WriteLine("----");
        String s;

        do
        {

            s = Console.ReadLine();
            Regex regex = new Regex("[0-9]");
            Regex regex2 = new Regex("[a-zA-Z]");
            if (regex.IsMatch(s))
            {
                if (regex.IsMatch(s) && regex2.IsMatch(s))
                {
                    Console.WriteLine("You entered an combination of number and String = " + s.ToString());
                }
                else
                {
                    int cnt = s.Count(x => x == '.');
                    if (s.Count(x => x == '.') > 1)
                    {
                        Console.WriteLine("Invalid input of number = " + s.ToString());
                    }
                    else if (s.Count(x => x == '.') == 1 && regex.IsMatch(s))
                    {
                        Console.WriteLine("You entered a decimal number = " + s.ToString());
                    }

                    else
                    {
                        char[] str = "!@#$%^&*()',-./:;<=>?@_`{|}~¡¢£¤¥¦§¨©¬®¯°±²³´µ¶¸¹º»¼½¾¿ÀÈËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöL÷øùúûüýþÿ\"".ToArray();
                        int indexOf = s.IndexOfAny(str);

                        if (indexOf == -1)
                        {

                            Console.WriteLine("You entered a number = " + s.ToString());

                        }
                        else
                        {
                            Console.WriteLine("You entered an combination of number and String = " + s.ToString());
                        }

                    }

                }
            }
            else
            {
                if (s.Trim().Length < 1)
                {
                    Console.WriteLine("Please enter any value.");
                }
                else
                {
                    Console.WriteLine("You entered a String = " + s.ToString());
                }

            }


        } while (s != null);
        Console.WriteLine("---");

答案 3 :(得分:-2)

首先将X定义为int,并且X将始终为int-type(),除非您转换此int类型,我认为使用try {...} catch {...}可能是一个很好的方法解决这个问题:

string x;
int result;
while (true)
{
    x = Console.ReadLine();
    try
    {
        result = int.Parse(x);
        Console.WriteLine("int input");
    }
    catch
    {
        Console.WriteLine("Invalid input ");
    }
}

或者您可以使用这样的正则表达式:

var reg = new Regex("^-?\\d+$");
string result;
Match m;
for (;;)
{
    result = Console.ReadLine();
    m = reg.Match(result);
    if(m.Success)
    {
        Console.WriteLine("int input");
    }
    else
    {
        Console.WriteLine("Invalid input: ");
    }
}