【问题标题】:c-string being saved to the end of another c-stringc-string 被保存到另一个 c-string 的末尾
【发布时间】:2015-02-25 05:55: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 book\n";
            repeat = 1;
        }
    }

    if (strlen(tempTitle) < 1 || strlen(tempTitle) > TITLE_SIZE)
    {
        cout << "The Book's title must be between 1 and 50 characters long\n";
        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 long\n";
        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-string保存到isbn c-string的末尾?

【问题讨论】:

    标签: c++ arrays structure getline c-strings


    【解决方案1】:

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

    您可以像这样进行有限长度的打印:

    printf("ISBN: %.13s\n", books[index].ISBN);
    

    【讨论】:

      【解决方案2】:

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

      char isbn[ISBN_SIZE];
      

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

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

      另外,如果isbn 的大小为ISBN_SIZE,那么不清楚你为什么使用表达式 (ISBN_SIZE) * 2 输入值。

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

      因此在输入值数据成员isbn 后不包含字符串的终止零。

      对应的sn-p代码如下

      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 long\n";
          }
      
      } while ( repeat );
      
      strcpy( bookArray[bookNumber].isbn, tempIsbn );
      

      同样的备注对输入书名有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多