Menu
CoddyTech

조기 종료와 건너뛰기

Coddy의 Lua 개발자를 위한 C++ 코스 레슨. 48개 중 10번째.

Lua에는 break는 있지만 continue는 없습니다. 반복의 나머지 부분을 건너뛰려면 루프 본문의 끝에 배치된 goto continue를 사용해 레이블로 이동합니다. C++에는 두 문이 모두 있으며, 가장 가까운 루프를 제어합니다. C++에서 break는 루프를 종료하고 continue는 다음 반복으로 넘어갑니다. 증가를 건너뛰게 되는 continue를 실행하기 전에 수동으로 관리하는 인덱스를 증가시키세요. ipairs와 마찬가지로 범위 기반 for문은 자체적으로 다음 항목으로 넘어갑니다.

Lua

local words = {"red", "", "blue", "STOP", "green"}
for _, word in ipairs(words) do
  if word == "STOP" then
    break
  end
  if word == "" then
    goto continue
  end
  print(word)
  ::continue::
end

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>

int main(){
std::vector<std::string> words={"red","","blue","STOP","green"};
size_t i=0;
while(i<words.size()){
  auto word=words[i++];
  if(word=="STOP")break;
  if(word.empty())continue;
  std::cout<<word<<"\n";
}
}

각 프로그램의 실행 과정을 독립적으로 추적해 보세요. 이 예시들은 과제와 다른 연산이나 데이터를 사용해 개념을 설명합니다. 원본과 대상의 출력이 일치한다고 가정하지 않습니다.

challenge icon

챌린지

쉬움

입력: 공백으로 구분된 정수입니다. 첫 번째 0이 나오기 전까지 양수 값을 더하고, 음수는 건너뛰며 0 이후의 값은 무시하세요.

exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 수정할 수 있습니다. 공개 시그니처는 그대로 유지하세요. 잠긴 main.cpp는 표준 입력을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API의 동작을 독립적으로 검사합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력값과 결과는 signed int의 범위에 들어갑니다. 별도 언급이 없는 한 텍스트는 ASCII입니다.

직접 해보기

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);std::vector<int> v;int n;while(in>>n)v.push_back(n);std::cout<<positive_prefix(v)<<"\n";
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Lua 개발자를 위한 C++의 모든 레슨

직접 연습해 보세요: 온라인 C++ 컴파일러