#include <iostream>
#include <string.h>
usingnamespace std;
int mainchoice;
char bookname[100];
void tfiosdetails();
int main()
{
system("Color 1B");
A:
cout << "What do you want to do?" << endl;
cout << "[1] - Search an available book" << endl;
cout << "[2] - Exit the program" << endl;
cout << "Choice: ";
cin >> mainchoice;
if (mainchoice == 1)
{
system("cls");
cout << "Enter book name: ";
cin >> bookname;
if(strcmp(bookname, "fault in our stars") == 0)
{
system("cls");
cout << "It works";
system("pause");
}
strcmp only allows me to compare one word only but I need to compare a sentence. This is a program that allows user to search for a title of a book. Thank you guys!
No, strcmp() allows you to check if one C-string to another C-string even if the C-strings have many "words".
This is a program that allows user to search for a title of a book.
First the code you posted is not a program, it is a snippet from a program. Second the snippet you posted will not search for a title of a book. It only looks to see if one string is equal to "fault in our stars". Since you don't show how you defined and assigned a value to song I can't tell if it will ever work.
By the way your variable sentence will only contain one word, not a sentence.
Using just cin will stop reading at whitespace, so it'll only capture the first word. cin.getline will read up to the length provided (second argument) minus 1 or up to a specified delimiter (which is, be default, the newline character), whichever comes first.
But keep in mind that only 99 characters will be read, because one character is reserved for affixing '\0' to the end of what was read. Entering more than 99 characters will cause only 99 characters to be read, the fail bit to be set, and future calls to fail unless you clear it.
#include <iostream>
#include <cstring>
usingnamespace std;
int main()
{
int mainchoice;
char bookname[100];
cout << "What do you want to do?" << endl;
cout << "[1] - Search an available book" << endl;
cout << "[2] - Exit the program" << endl;
cout << "Choice: ";
cin >> mainchoice;
if (mainchoice == 1)
{
cout << "Enter book name: ";
cin.ignore(1000,'\n'); // <---
cin.getline(bookname, 100); // as recommended by gentleguy
if(strcmp(bookname, "team effort") == 0)
{
cout << "It works!!\n";
}
}
else
{
cout << "We're all done here ...\n";
}
return 0;
}
What do you want to do?
[1] - Search an available book
[2] - Exit the program
Choice: 1
Enter book name: team effort
It works!!
Program ended with exit code: 0