嘿我试图验证一个字符串。基本上我想要它做的是阻止用户输入除字符串以外的任何东西。这是我的代码:
**getString**
string getString(string str)
{
string input;
do
{
cout << str.c_str() << endl;
cin >> input;
}
while(!isalpha(input));
return input;
}
错误
Error 2 error LNK2019: unresolved external symbol "public: bool __thiscall Validator::getString(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?getString@Validator@@QAE_NV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "public: void __thiscall Player::information(void)" (?information@Player@@QAEXXZ) C:\Users\Conor\Documents\College\DKIT - Year 2 - Repeat\DKIT - Year 2 - Semester 1 - Repeat\Games Programming\MaroonedCA2\MaroonedCA2\Player.obj MaroonedCA2
Error 3 error LNK1120: 1 unresolved externals C:\Users\Conor\Documents\College\DKIT - Year 2 - Repeat\DKIT - Year 2 - Semester 1 - Repeat\Games Programming\MaroonedCA2\Debug\MaroonedCA2.exe MaroonedCA2
4 IntelliSense: no suitable conversion function from "std::string" to "int" exists c:\Users\Conor\Documents\College\DKIT - Year 2 - Repeat\DKIT - Year 2 - Semester 1 - Repeat\Games Programming\MaroonedCA2\MaroonedCA2\Validator.cpp 72 17 MaroonedCA2
主要
cout << "What is your name ?\n";
name = validator.getString();<------This skips.
cout << "\nWhat is your age? ";
age = validator.getNum();
string character = "What is your sex M/F?";
sex = validator.getChar(character);
cout <<"Name:\n"<< name<<" Age:\n" << age<< " Sex:\n"<< sex <<"\n";
新的getString函数。
string Validator :: getString()
{
string input;
do
{
}
while (
std::find_if_not(
std::begin(input), //from beginning
std::end(input), //to end
isalpha //check for non-alpha characters
) != std::end(input) //continue if non-alpha character is found
);
return input;
}
答案 0 :(得分:2)
描述的第一个问题是这个函数属于一个类,但你忘了指定:
string Validator::getString(string str)
^^^^^^^^^^^
接下来,isalpha
需要int
(由于C原因),据我所知,std::string
没有版本。但是,您可以使用标准算法来执行此操作:
do {
...
} while (
std::find_if_not(
std::begin(input), //from beginning
std::end(input), //to end
isalpha //check for non-alpha characters
) != std::end(input) //continue if non-alpha character is found
);
此find_if_not
调用将搜索字符串,并通过将返回值与字符串的结束迭代器进行比较来检查是否找到任何非字母字符。如果它们相等,则字符串是干净的。您可能还需要投射isalpha
,因为它期望谓词采用char
,而不是int
。
对于使用此算法的某些示例,请参阅here。请注意,由于GCC的版本,std::begin()
和std::end()
已被替换,!=
由于函数的反向逻辑而更改为==
(您'使用它像do {} while (!ok(...));
)。
答案 1 :(得分:1)
isalpha
接受int而不是字符串。
确保字符串中每个字符都是字母的一种方法是做类似的事情。
bool isAlpha = false;
while (!isAlpha) {
// take in input blah blah
isAlpha = true;
for (unsigned i = 0; i < input.length(); ++i) {
if (!isalpha(input[i]))
isAlpha = false;
}
}
答案 2 :(得分:0)
更有效的方法是使用std::string
函数在字符串中搜索数字:
static const char digits[] = "0123456789";
isAlpha = text.find_first_of(digits, 0); // start from position 0.