+ 4
Can we compare strings from user input?
There are two string values entered char a[5]=Yes; char b[5] ;//which is a user input; If b[5] is equal to yes then print true other wise print false. Show it by programming a code.
4 Answers
+ 2
C++:
#include <iostream>
#include <string>
int main()
{
std::string s1 = "Hello";
std::string s2;
std::cout << "Enter a string: ";
std::cin >> s2;
// Works because of operator overloading
// You can also use !s1.compare(s2)
if (s1 == s2)
std::cout << "Strings are equal!\n";
else
std::cout << "Strings are not equal!\n";
return 0;
}
C:
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *s1 = "Hello";
char s2[32];
fputs("Enter a string: ", stdout);
scanf("%31s", s2);
if (!strcmp(s1, s2))
puts("Strings are equal.");
else
puts("Strings are not equal.");
return 0;
}
Python:
s1 = "Hello"
print("Enter a string:", end = ' ')
s2 = input()
if s1 == s2:
print("Strings are equal.")
else:
print("Strings are not equal.")
+ 1
yes ,you can compare input strings and string literals in C with strcmp() and in C++ with == or compare() for std::string. In python you can compare two strings with ==.
+ 1
Show me any code
0
Strings can not be compared using the == comparison operator so strcmp() should be used here.