“已启动”变量在此代码中做什么

What does the `started` variable do in this code?

本文关键字:代码 什么 变量 启动 已启动      更新时间:2023-10-16

谁能解释一下这段代码是如何工作的?

 #include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, char const *argv[])
{
     float longitude;
     float latitude;
     char info[80];
     int started = 0;
     cout << "Data = {";
     while (scanf("%f, %f, %79[^n]", &latitude, &longitude, info) == 3)
     {
         if(started)
             printf(",n");
         else
             started = 1;
         printf("{latitude: %f, longitude: %f, info: '%s'}",latitude, longitude, info);
     }
     return 0;
}

我不明白为什么使用 started 变量。为什么选中此变量的值而始终设置为 0?谁能为我逐行解释这段代码?

我不知道为什么在此代码中使用启动变量?

started变量用于确定这是否是第一次通过循环。 在第二次和以后的刀路中,将打印换行符,因此您不会总是在同一行上打印。

基本上,此代码执行一个循环,重复读取 3 个值(直到用户在不键入 3 个值的情况下按 Enter 键),并将它们打印出来。 第一次,不打印换行符,但每隔一次,将打印出逗号+换行符。

scanf() 3进入循环返回值,

while(scanf("%f, %f, %79[^]", &latitude, &longitude, info) == 3){

started被声明为0时,if无法执行else部分,

if(started)
      printf(",n");

else中,开始变成1

  else
     started = 1;

打印三个值,

   printf("{latitude: %f, longitude: %f, info: '%s'}",latitude, longitude, info);

在这里started 1打印n直到scanf()不等于3退出 while 循环,

}

注意"started = 1;"。

在循环的第一次运行时,无需添加逗号分隔符。赋值后,逗号将在每个参数后添加。