奇怪的字符出现在输入字符串的位置
Weird characters appearing in place of inputted strings
我正在开发一个 C++ 程序,该程序将字符串作为输入并以特定方式对其进行操作。这是代码:
string input;
cin >> input;
char arg = input[4]; //All inputs always have 5 characters
cout << arg << endl;
输入:加d
我原以为它会在屏幕上打印 d 但什么也没打印
另外,对于其他输入,我有时会得到奇怪的字符(比如上面有两个点的 y)作为输出。
为什么会发生这种情况,如何纠正?
注意 operator<< 对 std::string
的提取在空格处停止,因此 input
的值将是 add
,那么 char arg = input[4];
是 UB .
... then reads characters from is
and appends them to str
as if by
str.append(1, c)
, until one of the following conditions becomes
true:
...
std::isspace(c,is.getloc())
is true
for the next character c
in is
(this whitespace character remains in the input stream).
您可以使用 std::getline 代替读取包含空格的输入,它将读取字符串直到指定的分隔符;默认的是端线。例如
string input;
std::getline(std::cin, input);
在您的示例中,当您输入(添加 d)时,仅考虑 space 之前的字符。
所以 input[4]
中有垃圾值
如果要输入spaces,请使用双引号。
#include <iostream>
using namespace std;
int main(void)
{
string input;
cin >> input;
char arg = input[4]; //All inputs always have 5 characters
cout << input.length() << endl;
cout << arg << endl;
}
如果你通过add d,字符串长度将是3,而不是5。
如果你希望能够输入 spaces,替换 cin >> input;
std::getline(std::cin, input);
你会得到想要的结果。
在您的输入字符串中,cin
>>
运算符获取您的字符串,直到 space 然后它将终止。所以在你的字符串中只有 add
会出现,所以当你尝试访问第四个字符并打印时,不会显示任何内容。
试试,
string input;
getline(cin, input);
char arg = input[4];
cout << arg << endl;
我正在开发一个 C++ 程序,该程序将字符串作为输入并以特定方式对其进行操作。这是代码:
string input;
cin >> input;
char arg = input[4]; //All inputs always have 5 characters
cout << arg << endl;
输入:加d
我原以为它会在屏幕上打印 d 但什么也没打印 另外,对于其他输入,我有时会得到奇怪的字符(比如上面有两个点的 y)作为输出。
为什么会发生这种情况,如何纠正?
注意 operator<< 对 std::string
的提取在空格处停止,因此 input
的值将是 add
,那么 char arg = input[4];
是 UB .
... then reads characters from
is
and appends them tostr
as if bystr.append(1, c)
, until one of the following conditions becomes true:
...
std::isspace(c,is.getloc())
istrue
for the next characterc
inis
(this whitespace character remains in the input stream).
您可以使用 std::getline 代替读取包含空格的输入,它将读取字符串直到指定的分隔符;默认的是端线。例如
string input;
std::getline(std::cin, input);
在您的示例中,当您输入(添加 d)时,仅考虑 space 之前的字符。 所以 input[4]
中有垃圾值如果要输入spaces,请使用双引号。
#include <iostream>
using namespace std;
int main(void)
{
string input;
cin >> input;
char arg = input[4]; //All inputs always have 5 characters
cout << input.length() << endl;
cout << arg << endl;
}
如果你通过add d,字符串长度将是3,而不是5。
如果你希望能够输入 spaces,替换 cin >> input;
std::getline(std::cin, input);
你会得到想要的结果。
在您的输入字符串中,cin
>>
运算符获取您的字符串,直到 space 然后它将终止。所以在你的字符串中只有 add
会出现,所以当你尝试访问第四个字符并打印时,不会显示任何内容。
试试,
string input;
getline(cin, input);
char arg = input[4];
cout << arg << endl;