为什么在 cin.read() 请求另一个输入之前有 4 个空格?
Why are there 4 spaces before asking for another input by cin.read()?
当我从 'System.out.println' 中删除 'ln' 时,cin.read() 要求我在下一行输入,但是当我放回 'ln' 时,有 4在它问我另一个输入之前有空格,为什么?
InputStreamReader cin = new InputStreamReader(System.in);
char c;
do {
c = (char) cin.read();
System.out.println(c);
} while(c != 'q');
InputStreamReader
并非旨在从 System.in
的客户端输入中读取字符。它是从字节到字符的桥梁。
InputStreamReader.read()
确实会逐字节读取,包括表示由回车类型产生的行分隔符的字节。
因此,当您输入标准输入时,例如 x
然后单击 Enter
,根据您的 OS 读取 2 或 3 个字节并解码为字符。
x
\r
\n
对于基于 Windows OS 和 x
\n
对于基于 OS 的 Unix。
当您注意到 4 条换行符(3 条用于读取字节 + 1 条在您输入输入触摸后自动添加)时,您很可能处于 Windows。
要从标准输入中读取文本,Scanner
更合适,例如:
Scanner cin = new Scanner(System.in);
String word;
do {
word = cin.next();
System.out.println(word);
} while (!word.equals("q"));
当我从 'System.out.println' 中删除 'ln' 时,cin.read() 要求我在下一行输入,但是当我放回 'ln' 时,有 4在它问我另一个输入之前有空格,为什么?
InputStreamReader cin = new InputStreamReader(System.in);
char c;
do {
c = (char) cin.read();
System.out.println(c);
} while(c != 'q');
InputStreamReader
并非旨在从 System.in
的客户端输入中读取字符。它是从字节到字符的桥梁。
InputStreamReader.read()
确实会逐字节读取,包括表示由回车类型产生的行分隔符的字节。
因此,当您输入标准输入时,例如 x
然后单击 Enter
,根据您的 OS 读取 2 或 3 个字节并解码为字符。
x
\r
\n
对于基于 Windows OS 和 x
\n
对于基于 OS 的 Unix。
当您注意到 4 条换行符(3 条用于读取字节 + 1 条在您输入输入触摸后自动添加)时,您很可能处于 Windows。
要从标准输入中读取文本,Scanner
更合适,例如:
Scanner cin = new Scanner(System.in);
String word;
do {
word = cin.next();
System.out.println(word);
} while (!word.equals("q"));