需要设置数组字符串长度,使其正好为13

时间:2013-06-17 14:48:32

标签: c++

您好,我目前正在大学完成一个项目,但需要将长度设置为13,如果它比我的代码短13或更长,它将返回错误消息

 void add_new_text_book()
 {
//this option is here to add a new book to the list
printf("Please enter the Title of a new text book\n");
scanf("%s",book[number_of_books].title);
printf("Please enter the Authors firstname\n");
scanf("%s",book[number_of_books].firstname);
printf("Please enter the Author surname\n");
scanf("%s",book[number_of_books].surname);

printf("Finally please enter the ISBN number of the book\n");
scanf("%s",book[number_of_books].isbn);

if(length_of_string==13)//will be used to check the length of the book is valid

{
    if(number_of_books==15)//will check to see how many records have been used
    {
    printf("book not added as you have used all free space\n");
    }else
    {
    printf("Book has been added to the libary\n");
    number_of_books=number_of_books+1;
    }

}else{
printf("You have entered too many or few characters the books has not been saved\n");
}

getch();
    length_of_string=strlen(book[number_of_books].isbn);

但即使我输入13它也会出现错误消息,它似乎只接受123-456-789-1任何帮助都将被大大接受

3 个答案:

答案 0 :(得分:0)

您可以使用str.size()进行计算。

取自C ++参考

// string::size
#include <iostream>
#include <string>

int main ()
{
std::string str ("Test string");
std::cout << "The size of str is " << str.size() << " characters.\n";
return 0;
}

答案 1 :(得分:0)

“length_of_string”的值是多少? 它的价值是:123-456-789-1? 如果是这样,你可以使用它:

if(length_of_string.size()==13)//will be used to check the length of the book is valid


 {
    if(number_of_books.size()==15)//will check to see how many records have been used

 {
    printf("book not added as you have used all free space\n");

  }else

 {
    printf("Book has been added to the libary\n");
    number_of_books=number_of_books+1;

  }

  }
else

    {
  printf("You have entered too many or few characters the books has not been saved\n");

     }

getch();

   }

答案 2 :(得分:0)

如果您在使用之前计算length_of_string,而不是之后计算,则会有很大帮助。