无法获取 C++ 中字符串的大小 visual studio
cannot get the size of a string in C++ visual studio
我编写了一个简单的程序来删除字符串中的字母,并在键入时使用退格键。它应该每次都获取字符串的长度并删除最后一个字符,但我无法让函数 .length();
在我的程序中工作,我看到它被另一个人在 Whosebug 中使用。
Event eventInput;
string stringLength;
String userInput;
Text userText;
while (window.pollEvent(eventInput))
{
if (eventInput.type == sf::Event::TextEntered)
{
if (Keyboard::isKeyPressed(Keyboard::Backspace))
{
stringLength = userInput.length();
userInput.erase(1, 1);
}
userInput += eventInput.text.unicode;
userText.setString(userInput);
}
}
它说sf::String
没有成员长度
问题是您(和您的代码)混淆了两种不同类型的字符串。 String
和 string
不一样。似乎您需要名为 String
的 SFML 字符串 class。获取 SFML 字符串长度的方法称为 getSize
而不是 length
.
如果您不将 using namespace sf;
和 using namespace std;
添加到您的代码中,您将避免一些这种混淆。
您的代码中的另一个错误是退格键的处理。您的代码在检测到退格键时会删除一个字符,但随后会再次将其添加回去。这是因为您的代码在应该包含 if ... else
语句时包含了 if
语句。像这样
if (Keyboard::isKeyPressed(Keyboard::Backspace))
{
stringLength = userInput.length();
userInput.erase(1, 1);
}
else
{
userInput += eventInput.text.unicode;
userText.setString(userInput);
}
您将学到的其中一件事是查看您的代码并了解它的真实含义。
我编写了一个简单的程序来删除字符串中的字母,并在键入时使用退格键。它应该每次都获取字符串的长度并删除最后一个字符,但我无法让函数 .length();
在我的程序中工作,我看到它被另一个人在 Whosebug 中使用。
Event eventInput;
string stringLength;
String userInput;
Text userText;
while (window.pollEvent(eventInput))
{
if (eventInput.type == sf::Event::TextEntered)
{
if (Keyboard::isKeyPressed(Keyboard::Backspace))
{
stringLength = userInput.length();
userInput.erase(1, 1);
}
userInput += eventInput.text.unicode;
userText.setString(userInput);
}
}
它说sf::String
没有成员长度
问题是您(和您的代码)混淆了两种不同类型的字符串。 String
和 string
不一样。似乎您需要名为 String
的 SFML 字符串 class。获取 SFML 字符串长度的方法称为 getSize
而不是 length
.
如果您不将 using namespace sf;
和 using namespace std;
添加到您的代码中,您将避免一些这种混淆。
您的代码中的另一个错误是退格键的处理。您的代码在检测到退格键时会删除一个字符,但随后会再次将其添加回去。这是因为您的代码在应该包含 if ... else
语句时包含了 if
语句。像这样
if (Keyboard::isKeyPressed(Keyboard::Backspace))
{
stringLength = userInput.length();
userInput.erase(1, 1);
}
else
{
userInput += eventInput.text.unicode;
userText.setString(userInput);
}
您将学到的其中一件事是查看您的代码并了解它的真实含义。