[英]C++ Weird char printing behavior
我嘗試編寫一段代碼,要求您在鍵盤上(隨機)鍵入某個鍵來訓練打字。 像這樣:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <ostream>
#include <string>
#include <time.h>
#include <vector>
using namespace std;
int main(void) {
string numbers = "1234567890"; // 0 -> 9
string letters = "azertyuiopqsdfghjklmwxcvbn"; // 10 -> 35
string letters_upp = "AZERTYUIOPQSDFGHJKLMWXCVBN"; // 36 -> 61
string letters_acc = "éèàçù"; // 62 -> 67
string symbols = "&'(-_ç)=#{[|`^@]}°+$£%*µ,?;.:/!§<>€\"\\"; //
//
string keybord = numbers + letters + letters_upp + letters_acc + symbols;
//
srand(time(NULL));
int index = rand() % keybord.size() - 1;
char search = keybord[index];
bool program_launched = true;
string rst;
while (program_launched) {
cout << "Please enter : " << search
<< " to go further (Enter 'quit' to quit)."
<< endl;
cin >> rst;
if (rst == "quit") {
cout << "The char was : " << index << endl;
program_launched = false;
} else if (rst[0] == search) {
index = rand() % keybord.size() - 1;
search = keybord[index];
cout << "Good answer !" << endl << endl;
} else {
cout << "Wrong answer !" << endl << endl;
}
}
}
問題是某些字符沒有正確打印在終端中,例如這可能發生:
請進一步輸入:� 至 go(輸入“quit”退出)。
我試圖逐個字符地打印整個字符串,看看哪個有問題:
for(int i = 0; i < keybord.size(); i++){
cout << keybord[i] << endl;
}
output 是:
1
2
3
4
5
6
7
8
9
0
a
z
e
r
t
y
u
i
o
p
q
s
d
f
g
h
j
k
l
m
w
x
c
v
b
n
A
Z
E
R
T
Y
U
I
O
P
Q
S
D
F
G
H
J
K
L
M
W
X
C
V
B
N
�
�
�
�
�
�
�
�
�
�
&
�
�
'
(
-
�
�
_
�
�
�
�
)
=
#
{
[
|
`
^
@
]
}
�
�
+
$
�
�
%
*
�
�
,
?
;
.
:
/
!
�
�
<
>
�
�
�
"
\
但是當我刪除<< endl
以獲得更好的可見性時,發生了這種情況:
1234567890azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBNéèàçù&é'(-è_çà)=#{[|`^@]}°+$£%*µ,?;.:/!§<>€"\
這意味着<< endl
以某種方式使終端中的字符變得奇怪。 我正在使用 UTF8 順便說一句。 (通過添加其他字符串來定義string keyboard
不是我實驗的問題)
你知道問題是什么以及如何解決嗎?
首先,在下面的代碼中,您有機會獲得值-1
:
int index = rand() % keybord.size() - 1;
所以有時你會得到一個未定義的行為。
但是 output 有和沒有std::endl
的區別是用多字節編碼解釋的。 您可能會觀察到某些字符用 2 個“奇怪的符號”表示。 如果你 output 他們沒有換行中斷,你會看到 Unicode 符號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.