gpt4 book ai didi

c++ - 如何防止将整数分配给 char 字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 16:07:17 24 4
gpt4 key购买 nike

我是 c++ 编程的新手,我遇到了这个我无法解决的问题。每当用户输入整数而不是字符时,我都试图创建一条错误消息。问题是,由于某种原因,整数被接受并分配给 char 字符串。我认为将字符串定义为 int 或 char 等的目的是让编译器知道要接受哪些值。谁能告诉我我做错了什么?

int x, input = false;
char check[SIZE], str[SIZE];

cout << "Enter one word: ";
cin >> str;

while (!cin)
{
cout << "\nERROR: You must enter only one word with characters. \n\nRe-enter: ";
cin.clear();
cin.ignore(256, '\n');
cin >> str;
}

最佳答案

首先,使用 std::string 而不是 char[]

其次,“2”是一个完全有效的字符串。

第三,您可以使用 find_first_of 或类似工具来检查字符串是否包含任何不需要的值。

std::string::size_t result = str.find_first_of("0123456789");
if (result != std::string::npos)
{
// Found an undesirable character
}

关于c++ - 如何防止将整数分配给 char 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33374203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com