c字符串被保存到另一个c字符串的末尾

c-string being saved to the end of another c-string

本文关键字:字符串 保存 另一个      更新时间:2023-10-16

我正在制作一个程序来存储图书馆的藏书。其中一个选项是将一本新书添加到一组结构中。

这是代码

do
{
    repeat = 0;
    cout << "Enter the book's title: ";
    cin.getline(tempTitle, (TITLE_SIZE) * 2);
    for (int i = 0; i < bookNumber; i++)
    {
        if (strcmp(tempTitle, bookArray[i].title) == 0)
        {
            cout << "That title has already been entered, please enter a new bookn";
            repeat = 1;
        }
    }
    if (strlen(tempTitle) < 1 || strlen(tempTitle) > TITLE_SIZE)
    {
        cout << "The Book's title must be between 1 and 50 characters longn";
        repeat = 1;
    }
} while (repeat == 1);
strncpy(bookArray[bookNumber].title, tempTitle, TITLE_SIZE);
file << bookArray[bookNumber].title << "n";

do
{
    repeat = 0;
    cout << "Enter the book's ISBN number: ";
    cin.getline(tempIsbn, (ISBN_SIZE) * 2);
    if (strlen(tempIsbn) != ISBN_SIZE)
    {
        cout << "The Book's title must be 13 digits longn";
        repeat = 1;
    }
} while (repeat == 1);
strncpy(bookArray[bookNumber].isbn, tempIsbn, ISBN_SIZE);

这是我的输入

Enter the book's title: new book title
Enter the book's ISBN number: 0000000000000
Enter the book's author: Person
Is the book currently in stock (y/n)? y

以下是保存为的内容

Title : new book title
ISBN #: 0000000000000Person
Author: Person
Status: Available

为什么要把作者c字符串保存到isbn c字符串的末尾?

book::ISBN似乎是一个13元素的char数组。如果将此数组传递给C字符串处理函数,则该函数只接收起始地址,而不接收长度,因此它会在内存中扫描数值为0的字节(而不是ASCII"0"),并将其视为字符串的末尾。ISBN中的十三个字符完全由数字填充,后面紧跟着作者,因此ISBN的打印一直持续到作者成员的终止0字节。

你可以像这样进行有限长度的打印,例如:

printf("ISBN: %.13sn", books[index].ISBN);

输入数据的逻辑无效。例如,如果数据成员isbn被定义为类似

char isbn[ISBN_SIZE];

如果ISBN_SIZE等于13,则该数据成员只能存储12位,因为数组的最后一个字符将存储终止零。

因此,如果您想要数据成员isbn,则应该将ISBN_SIZE定义为等于14。将存储CCD_ 8位数字。

同样,如果isbn的大小为ISBN_SIZE,则不清楚为什么要使用表达式(ISBN_SIZE) * 2以输入值。

cin.getline(tempIsbn, (ISBN_SIZE) * 2);

因此,在穿透值之后,数据成员isbn不包含字符串的终止零。

相应的代码片段可能看起来像

bool repeat = false; // the initialization only for exposition
do
{
    cout << "Enter the book's ISBN number: ";
    cin.getline( tempIsbn, ISBN_SIZE );
    if ( repeat = ( strlen( tempIsbn ) != ISBN_SIZE - 1 ) )
    {
        cout << "The Book's ISDN number must be " << ISBN_SIZE - 1 << " digits longn";
    }
} while ( repeat );
strcpy( bookArray[bookNumber].isbn, tempIsbn );

同样的备注也适用于输入书名。