-2

嗨,我目前正在大学完成一个项目,但需要将长度设置为 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 任何帮助都会被大大接受

4

3 回答 3

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;
}
于 2013-06-17T14:51:23.420 回答
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();

   }
于 2013-06-17T15:01:27.233 回答
0

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

于 2013-06-17T15:40:19.430 回答