C# 检查用户是否键入了文本验证-而

C# 检查用户是否键入了文本验证-而,c#,C#,我正在尝试编写一段代码,要求用户输入一些文本(到目前为止我已经有了),如果用户输入一个数字,它会再次要求输入文本,直到用户输入文本,而不是数字 string input; int value; Console.WriteLine("Type in some text: "); input = Console.ReadLine(); if (int.TryParse(inpu

我正在尝试编写一段代码,要求用户输入一些文本(到目前为止我已经有了),如果用户输入一个数字,它会再次要求输入文本,直到用户输入文本,而不是数字

            string input;
            int value;

            Console.WriteLine("Type in some text: ");
            input = Console.ReadLine();

            if (int.TryParse(input, out value))
            {
                Console.WriteLine("Please type in some text without numbers");
            }
            else
                Console.WriteLine(input); 
            Console.ReadLine();
我想可能需要一段时间,但不确定

感谢您的建议。

尝试一下:

static void Main(string[] args)
    {
        string input;

        Console.WriteLine("Type in some text: ");
        input = Console.ReadLine();

        while(input.Any(char.IsDigit))
        {
            Console.WriteLine("Please type in some text without numbers");
            input = Console.ReadLine();
        }
    }
你是对的-你确实需要一段时间的循环

您还可能有一个bug,因为文本
123kjhasd
不会解析为int,因此会被认为是有效的。如果您想检查所有文本是否都不是一个数字,可以使用LINQ,就像我上面所做的那样

如果我误解了,数字和字母的组合是可以的,那么一定要保持你的表情:

while(int.TryParse(input, out value)

你已经足够接近了,并且正确地认为需要一个循环

string input;
int value;

while (true) {
    Console.WriteLine("Type in some text: ");
    input = Console.ReadLine();

    if (!int.TryParse(input, out value))  // TryParse failed, we're good
    {
        Console.WriteLine(input);
        break;
    }

    Console.WriteLine("Please type in some text without numbers");
}

是的,你需要一个while循环。如果您将
If
更改为
while
并删除
else
,您将非常接近您所需要的。您只需要重复输入部分以及控制台输出。我假设
userInput
input
的打字错误,顺便说一句。“请键入一些没有数字的文本”可能表示该行为不是错误,而是故意的。是的,我可能错了。这句话的措辞让我相信他不是在找数字。我将保留我的答案,除非他澄清措辞。是的,我只希望输入接受字符。如果我想做相反的事情,它是否相似?检查它是否是数字,而不是文本?在(input.All(!char.IsDigit))