这只是我代码中的一小部分。我想做的是在文件的末尾写(添加记录(,在本例中是"books.txt",它已经有40条记录了。但当我调试时,它仍然会提示用户输入isbn代码,但在输入后,(过程3296(退出,代码为3。出来了。我做错了哪一部分?counter((函数用于计算我的文件中已经有多少条记录。我还使用结构数组来存储我的记录。
int add_record(DATA book[])
{
int count = counter();
system("CLS");
cout << "tttttttt : :Add Book Record: :nn";
bool cont;
ofstream outfile("books.txt", ios::app);
if (outfile.is_open() && !outfile.eof())
{
do
{
cont = true;
cout << "ISBN Code: ";
cin.getline(book[++count].isbn_code, 14, 'n');
//cin.ignore(numeric_limits<streamsize>::max(), 'n');
int length = strlen(book[++count].isbn_code);
for (int i = 0; i <= length; i++)
{
if (!isdigit(book[++count].isbn_code[i]))
{
cont = false;
cout << "Your input is invalid. Enter again.n";
break;
}
}
} while (cont == false);
do
{
cont = true;
cout << "Author: ";
cin.getline(book[++count].author, 50, 'n');
int length = strlen(book[++count].author);
for (int i = 0; i <= length; i++)
{
if (isdigit(book[++count].author[i]))
{
cont = false;
cout << "Your input is invalid. Enter again.n";
break;
}
}
} while (cont == false);
outfile << book[++count].isbn_code << "," << book[++count].author ;
outfile.close();
}
else
cout << "File is not openn";
return 0;
}
是的,错误消息完全正确。这是一种罕见的情况,其中使用强制转换是正确的做法做
if (isdigit(static_cast<unsigned char>(book[++count].author[i])))
参考文献,https://en.cppreference.com/w/cpp/string/byte/isdigit
但这与其他错误导致的崩溃无关。例如
cin.getline(book[++count].isbn_code, 14, 'n');
//cin.ignore(numeric_limits<streamsize>::max(), 'n');
int length = strlen(book[++count].isbn_code);
您绝对不想将count
增加两次。我猜正确的代码是
cin.getline(book[count].isbn_code, 14, 'n');
int length = strlen(book[count].isbn_code);
并且稍后在循环中增加CCD_ 2一次。
请记住,++count
与count + 1
不同。第一种方法增加count
变量,即改变count
变量的值,但count + 1
只是在count
上加一,而不改变count
变量的值。
这也是错误的
for (int i = 0; i <= length; i++)
在C++中,字符串索引从零开始,一直到字符串的长度减去一,因此正确的代码是
for (int i = 0; i < length; i++)
也不属于您的问题,但X
可以是ISBN中的法律字符。