C# ';当';与';而';

C# ';当';与';而';,c#,c++,c,while-loop,do-while,C#,C++,C,While Loop,Do While,可能的重复项: 我已经编程有一段时间了(2年的工作+4.5年的学位+1年的大学预科),在编程入门课程中,我从未使用过一个do-while循环。我越来越觉得,如果我从来没有遇到过如此基本的事情,我的编程就错了 可能是我没有遇到正确的情况吗 有哪些示例需要使用do while而不是while (我的学校教育几乎都是C/C++的,我的工作是C#,所以如果有另一种语言是绝对有意义的,因为它们的工作方式不同,那么这些问题就不适用了。) 为了澄清……我知道while和do while之间的区别。Whil

可能的重复项:

我已经编程有一段时间了(2年的工作+4.5年的学位+1年的大学预科),在编程入门课程中,我从未使用过一个do-while循环。我越来越觉得,如果我从来没有遇到过如此基本的事情,我的编程就错了

可能是我没有遇到正确的情况吗

有哪些示例需要使用do while而不是while

(我的学校教育几乎都是C/C++的,我的工作是C#,所以如果有另一种语言是绝对有意义的,因为它们的工作方式不同,那么这些问题就不适用了。)


为了澄清……我知道
while
do while
之间的区别。While检查退出条件,然后执行任务<代码>执行任务时执行,然后检查退出条件。

如果您总是希望循环至少执行一次。这并不常见,但我确实经常使用它。您可能希望使用它的一种情况是尝试访问可能需要重试的资源,例如:

do
{
   try to access resource...
   put up message box with retry option

} while (user says retry);

do while
是指您希望至少运行一次代码块<另一方面,代码>while不总是根据指定的条件运行。

当循环检查循环前的条件时,
执行…当循环检查循环后的条件时。如果您希望根据循环运行的副作用来确定条件,或者像其他海报所说的那样,如果您希望循环至少运行一次,那么这很有用

我知道你是从哪里来的,但是,
do-while
是大多数人很少使用的东西,我从来没有使用过自己。你没有做错


你没有做错。这就好比说有人做错了,因为他们从未使用过
字节
原语。只是没有那么常用。

如果编译器不能胜任优化,那么使用while更好。do while只有一个条件跳转,而for和while有一个条件跳转和一个无条件跳转。对于流水线且不进行分支预测的CPU,这会对紧密循环的性能产生很大影响


此外,由于大多数编译器都非常聪明,可以执行此优化,因此反编译代码中发现的所有循环通常都会在执行时执行(如果反编译程序甚至懒得从向后的本地GOTO重构循环)。

我在学校时曾多次使用过它们,但从那以后就没有这么多了

理论上,当您希望在退出条件检查之前执行一次循环体时,它们非常有用。问题是,对于不希望首先检查的少数情况,通常希望退出检查在循环体的中间,而不是最后。在这种情况下,我更喜欢使用著名的
for(;;)
if(condition)exit身体的某个地方


事实上,如果我对循环退出条件有点不确定,有时我会发现在需要的地方用exit语句将循环编写为(;;){}
,然后当我完成时,我可以看到是否可以通过移动初始化、退出条件来“清理”循环,和/或为
的括号增加
中的代码。

当您想至少执行一次某项操作时,Do while非常有用。至于使用do while和while的一个很好的例子,让我们假设您想制作以下内容:一个计算器

您可以通过使用循环并在每次计算后检查人员是否要退出程序来实现这一点。现在,您可以假设,一旦程序打开,此人至少要执行一次,因此您可以执行以下操作:

do
{
    //do calculator logic here
    //prompt user for continue here
} while(cont==true);//cont is short for continue

到目前为止的答案总结了do while的一般用法。但是OP要求提供一个例子,所以这里有一个:获取用户输入。但是用户的输入可能是无效的-因此您请求输入,验证它,如果它有效则继续,否则重复


使用do while,您可以在输入无效时获取输入。使用常规的while循环,您只会获取一次输入,但如果输入无效,您会一次又一次地获取它,直到它有效为止。不难看出,如果循环体变得更复杂,则前者更短、更优雅,维护更简单。

我在读取文件开头的哨兵值时使用了
do,但除此之外,我不认为这种结构不太常用是不正常的--
do,而
s实际上是情境性的

-- file --
5
Joe
Bob
Jake
Sarah
Sue

-- code --
int MAX;
int count = 0;
do {
MAX = a.readLine();
k[count] = a.readLine();
count++;
} while(count <= MAX)
--文件--
5.
乔
上下快速移动
满意的
莎拉
控告
--代码--
int MAX;
整数计数=0;
做{
MAX=a.readLine();
k[count]=a.readLine();
计数++;

}while(count我编程大约12年了,就在3个月前,我遇到了这样一种情况,使用do-while确实很方便,因为在检查条件之前,一次迭代总是必要的。因此,我猜你的大好时机就在前面:)。

我在trydeletectory函数中使用了它。是这样的

do
{
    try
    {
        DisableReadOnly(directory);
        directory.Delete(true);
    }
    catch (Exception)
    {
        retryDeleteDirectoryCount++;
    }
} while (Directory.Exists(fullPath) && retryDeleteDirectoryCount < 4);
do
{
尝试
{
DisableReadOnly(目录);
目录。删除(true);
}
捕获(例外)
{
retryDeleteDirectoryCount++;
}
}while(Directory.Exists(fullPath)&&retryDeleteDirectoryCount<4);

一种情况,您总是需要运行一段代码一次,并且根据其结果,可能需要运行更多次。常规
while
循环也可以产生相同的结果

rc = get_something();
while (rc == wrong_stuff)
{
    rc = get_something();
}

do
{
    rc = get_something();
}
while (rc == wrong_stuff);

我遇到的最常见的场景是使用
do
/
,而
循环在一个小控制台程序中,该程序基于一些输入运行,并将根据用户的喜好重复多次。显然,控制台程序不运行任何时间是没有意义的;但是,除了第一次由用户决定之外——因此,
do
/
while
而不仅仅是
do
{
   int input = GetInt("Enter any integer");
   // Do something with input.
}
while (GetBool("Go again?"));
using(IDataReader reader = connection.ExecuteReader())
{
    do
    {
        while(reader.Read())
        {
            //Read record
        }
    } while(reader.NextResult());
}
# some comments
# some more comments
column1 column2
  1.234   5.678
  9.012   3.456
    ...     ...
do {
    line = read_line();
} while ( line[0] == '#');
/* parse line */
do
    display options
    get choice
    perform action appropriate to choice
while choice is something other than exit
do {
 A;
 if (condition) INV=false; 
 B;
} while(INV);
INV=true;
while(INV) {
 A;
 if (condition) INV=false; 
 B;
}
while(INV) {
     A;
     if (condition) INV=false; 
     B;
}
if (INV) {
 do
 {
         A;
         if (condition) INV=false; 
         B;

 } while(INV)
}
char *next_utf8_character(const char *txt)
{
    if (!txt || *txt == '\0')
        return txt;

    do {
        txt++;
    } while (((signed char) *txt) < 0 && (((unsigned char) *txt) & 0xc0) == 0xc0)

    return (char *)txt;
}
do
{
   ...
} while (0)
#define compute_values     \
   area = pi * r * r;      \
   volume = area * h
r = 4;
h = 3;
compute_values;
if (shape == circle)  compute_values;
if (shape == circle) area = pi *r * r;
volume = area * h;
if (shape == circle)
  do
  {
    area = pi * r * r;
    volume = area * h;
  } while (0);
do
{
    GetProspectiveResult();
}
while (!ProspectIsGood());
DOWHILE (no shutdown requested)
   determine timeout
   wait for work(timeout)
   IF (there is work)
      REPEAT
          process
      UNTIL(wait for work(0 timeout) indicates no work)
      do what is supposed to be done at end of busy period.
   ENDIF
ENDDO
DOWHILE (no shutdown requested)
   determine timeout
   wait for work(timeout)
   IF (there is work)
      set throttle
      REPEAT
          process
      UNTIL(--throttle<0 **OR** wait for work(0 timeout) indicates no work)
   ENDIF
   check for and do other (perhaps polled) work.
ENDDO
response_buffer = []
char_read = port.read(1)

while char_read:
    response_buffer.append(char_read)
    char_read = port.read(1)

# When there's nothing to read after 1s, there is no more data

response = ''.join(response_buffer)
do:
    char_read = port.read(1)
    response_buffer.append(char_read)
while char_read
response_buffer = []
char_read = None

while char_read != '':
    char_read = port.read(1)
    response_buffer.append(char_read)

response = ''.join(response_buffer)
    //This will skip the first row because Read() returns true after advancing.
    while (_read.NextResult())
           {
               list.Add(_read.GetValue(0).ToString());
           }

   return list;
    //This will make sure the currently read row is added before advancing.
    do
        {
            list.Add(_read.GetValue(0).ToString());
        } 
        while (_read.NextResult());

    return list;
/* skip the line */
do {
    c = getc(fp);
} while (c != '\n');
int c;  // another classic bug is to define c as char.
while ((c = getc(fp)) != EOF && c != '\n')
    continue;
for (;;) {
    int c = getc(fp);
    if (c == EOF || c == '\n')
        break;
}
Console.WriteLine("hoeveel keer moet je de zin schrijven?");
        int aantal = Convert.ToInt32(Console.ReadLine());
        int counter = 0;

        while ( counter <= aantal)
        {
            Console.WriteLine("Ik mag geen stiften gooien");
            counter = counter + 1;
string fileName = string.Empty, fullPath = string.Empty;

while (string.IsNullOrEmpty(fileName) || File.Exists(fullPath))
{
    fileName = Guid.NewGuid().ToString() + fileExtension;
    fullPath = Path.Combine(uploadDirectory, fileName);
}
string fileName = string.Empty, fullPath = string.Empty;

do
{
    fileName = Guid.NewGuid().ToString() + fileExtension;
    fullPath = Path.Combine(uploadDirectory, fileName);
}
while (File.Exists(fullPath));