c字符串被保存到另一个c字符串的末尾
c-string being saved to the end of another c-string
我正在制作一个程序来存储图书馆的藏书。其中一个选项是将一本新书添加到一组结构中。
这是代码
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 );
同样的备注也适用于输入书名。
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- C++.我想将更改后的特定字符行保存在字符串中
- 保存名称或字符串
- C++ 将地址保存为字符串的向量转换为新的向量
- C++读取大文件并将其保存到字符串中,然后删除特定的随机单词
- C++以尽可能快的速度逐行将字符串保存到文件中
- 如何在c++中将字符串中的所有数字保存到多维数组中
- 如何将字符串保存在最长的常见子序列递归算法中
- 如果我不将预先编写的字符串保存到变量,它还在内存中吗?
- 仅将纪元字符串保存到 mysql 日期时间年/月/日,但没有小时分钟秒
- 将字符串保存在集合中时,C_STR()仍然有效
- 分类一个向量,该向量由该类中的成员字符串保存对象
- 如何拆分 QString 并将一部分字符串保存在浮点数的向量中
- 为什么第二个字符串保存在第一个字符串中
- C++ 如何将 argv 作为字符串保存到矢量
- 在C++中使用字符指针将字符串保存到类属性
- 如何将字符串保存为二进制文件
- 将字符串保存到重载括号中,不改变对象的字段
- 如何在标记后将字符串保存在数组中
- 我如何将base64字符串保存为Qt中的png图像