简体   繁体   中英

How to use Console.ReadLine() in a while statement

Im looping a question untill the user puts in the value i want to accept. In this case its a number with a dash and it should be 7 'symbols' long.

My problem is putting the ReadLine inside of the while() statement.

So this is my code:

string cpr = "";
do
{

cpr = Console.ReadLine(); //I dont want ReadLine here :/

} while (
//I want Console.ReadLine() here
cpr.Length != 7
&&
!Regex.IsMatch(cpr, @"^[0-9-]+$")
&&
Regex.IsMatch(cpr, @"^[a-z]+$")
);

Putting ReadLine in a while statement is possible i have some other code that works while try parsing an int

do
{
//do something here
} while (!int.TryParse(Console.ReadLine(), out int1));

Try something like this:

            string cpr = "";
            bool condition = true;
            while (condition )
            {
                cpr = Console.ReadLine();
                if(cpr is ok)
                {
                    condition = false;
                }
            }

While I agree with the comments (in that this isn't the best way to approach this - in fact, the code you've provided is more than adequate), you can do assignment inside of a conditional statement. ie.

var str = "";
do
{
...
} while ((str = Console.ReadLine()).Length != 7 && Regex.IsMatch(str, ...));

Except in this case, you'd need to use a while loop, instead of a do-while (since you won't capture input until the end of the loop with the do-while pattern).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM