+ 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.

13th May 2020, 8:07 AM
Atul Prakash
Atul Prakash - avatar
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.")
13th May 2020, 8:34 AM
Gen2oo
Gen2oo - avatar
+ 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 ==.
13th May 2020, 8:24 AM
Gen2oo
Gen2oo - avatar
+ 1
Show me any code
13th May 2020, 8:25 AM
Atul Prakash
Atul Prakash - avatar
0
Strings can not be compared using the == comparison operator so strcmp() should be used here.
21st May 2020, 7:51 AM
Arju Kumari