【发布时间】:2021-11-20 21:22:09
【问题描述】:
尝试创建一个程序,该程序从文本文件中读取单词并输出 20 个密码组合,每个密码组合 4 个单词,并且具有某些条件,例如单词中没有标点符号,没有数字,并且除第一个以外的字符不能为大写。但是,我在 ispunct(b[i]) 处抛出异常,我认为这与单词大小的变化有关,但我不确定。任何帮助都将不胜感激,因为我对 C++ 的了解充其量只是初级知识。
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
bool acceptWord(string a, string b) {
if (b.length() > 3) {
for (int i = b.length() - 1; i; --i) {
if (ispunct(b[i])) {
return false;
}
if (isdigit(b[i])) {
return false;
}
}
if (isalpha(b[0]) && isupper(b[0])) {
for (int i = b.length(); i; --i) {
if (isupper(b[i])) {
return false;
}
}
}
a = b;
return true;
}
else {
return false;
}
}
int main()
{
fstream file;
string word, filename;
vector<string> tokens;
int random = rand() % 81;
filename = "input.txt";
file.open(filename.c_str());
if (!file.is_open()) {
cout << "File not found" << endl;
exit(1);
}
while (file >> word)
{
string token = "";
if (acceptWord(token, word)) {
for (int i = 0; i < 80; ++i) {
tokens[i] = token;
}
}
for (int i = 0; i < 20; ++i) {
cout << tokens[random] + " " + tokens[random] + " " + tokens[random] + " " + tokens[random] + "1" << endl;
}
}
return 0;
}
【问题讨论】:
-
很明显,告诉我们您遇到的什么异常会很有帮助...
-
它只是说,当我尝试运行程序时,它在 ispunct(b[i]) 处触发了断点。
-
这并没有解决问题,而是养成使用有意义的值初始化对象的习惯,而不是默认初始化它们并立即覆盖默认值。在这种情况下,这意味着将
fstream file; ... file.open(filename.c_str());更改为... fstream file(filename.c_str());,或者更好的是... fstream file(filename);。 -
出现错误时
b中的单词是什么?ispunct不支持带负值的带符号字符(EOF 除外),因此如果您的字符串中有扩展 ASCII 字符,并且您的编译器对char类型进行了签名,您可能会遇到问题。跨度> -
“触发断点”:你有设置断点吗?
标签: c++