CS50x threads to aide as a supplementary resource › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 3: [Algorithms] – Linear Search, Binary Search, Bubble Sort, Selection Sort, Recursion, Merge Sort › What is wrong in this program taking input of string characters
Tagged: arrays, linear search, string comparison, string type
- This topic is empty.
-
AuthorPosts
-
March 15, 2022 at 11:00 am #262
#include #include #include int main(void) { int s = 5; string lib
; for (int i = 0; i < s; i++) { lib = get_string("enter text"); } int t = (sizeof(lib)/sizeof(lib[0])); printf("no. of elements: %i\n",t); for(int p = 0; p < t; p++) { if(lib[p] == 'a') { printf("found a"); return 1; } } printf("not found"); }I intend to have the user enter five times a string of text characters.
Reply
You declared a string of size s, but in the user input, you are instead inputting strings. If you want to store a list of 5 strings, you need an array of strings.
Aka: you are storing strings in a string
What are you trying to do? Is this program checking if the user entered the letter ‘a’ as input? If so you would be better served by the function
get_char
from the cs50 library.
OP
I intend to have user enter five chunk of texts: Say user enters:
-
boy
-
bbb
-
rrere
-
erere
-
erere
Then check if say ‘boy’ found.
Reply
ou’ll need the
strcmp()
function fromstring.h
then.for(int p = 0; p < 5; p++) { if(strcmp(lib[p], "boy") == 0) { printf("found boy\n"); return 0; // return 0 from main to indicate success } } return 1; // returning 1 from main is used to indicate a fail state
OP
Without return 1 as well, the program apparently works. So is including that a matter of choice?
Only if you want the return value of your program to indicate whether something was found or not.
If the output of “found boy” is sufficient, then no you don’t really need the return 1.
[learn_press_profile]
-
-
AuthorPosts
- You must be logged in to reply to this topic.