入力を読み取るための通常の Java 規則は次のとおりです。
import java.io.*;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String strLine;
while ((strLine = br.readLine()) != null) {
// do something with the line
}
入力を読み取るための通常の C++ 規則は次のとおりです。
#include <iostream>
#include <string>
std::string data;
while(std::readline(std::cin, data)) {
// do something with the line
}
そしてCでは、それは
#include <stdio.h>
char* buffer = NULL;
size_t buffer_size;
size_t size_read;
while( (size_read = getline(&buffer, &buffer_size, stdin)) != -1 ){
// do something with the line
}
free(buffer);
または、ファイル内のテキストの最も長い行の長さを知っていると確信している場合は、次のことができます。
#include <stdio.h>
char buffer[BUF_SIZE];
while (fgets(buffer, BUF_SIZE, stdin)) {
//do something with the line
}
ユーザーがコマンドを入力したかどうかをテストする場合quit
、これら 3 つのループ構造のいずれかを簡単に拡張できます。私はあなたのためにJavaでそれをします:
import java.io.*;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = br.readLine()) != null && !line.equals("quit") ) {
// do something with the line
}
break
したがって、またはが正当化されるケースは確かにありgoto
ますが、ファイルまたはコンソールから 1 行ずつ読み取るだけの場合は、ループを実行する必要はありませんwhile (true)
。プログラミング言語が既に提供しています。入力コマンドをループ条件として使用するための適切なイディオムを使用します。