Thread: Trying to use strstr

  1. #16
    Registered User
    Join Date
    May 2010
    Posts
    35
    Quote Originally Posted by claudiu View Post
    To sum things up:

    1) Learn to read a STRING from the console like Subsonics suggested.

    2) Change the function checkString prototype to what has been suggested.

    This should take you literally 2 minutes.
    Here is my new code based on all the suggestions. Obviously I'm too stupid to figure this out. Since it should take 2 minutes and its taken me way too long.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    void checkString(char c);
    
    int main()
    {
       char c[50];
       fgets(c, 50, stdin);
    
       while (c != EOF)
       {
          checkValue(c);
          c = getchar();
       }
       return(0);
    }
    
    void checkString(char *c)
    {
       char *ptr_to_string = malloc(sizeof(char) * 100);
       strcpy(ptr_to_string, *c);
       char *find = strstr(ptr_to_string, "lb");
       if (*find != null)
       {
          puts("Input contains lb");
       }
    }

  2. #17
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Dude. I don't know why you haven't figured this out with all the capitals and the italics.

    If you type "char" in your program IT DOES NOT MEAN STRING. STOP STOP STOP STOP and think for, yes, two minutes. DO NOT USE CHAR. Do not come back until you have something other than a char in your program.

  3. #18
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    fxtdr79, your function should work as is if you only change to checkString(char *c), like you've done.
    You won't need your while loop or the getchar if you use fgets. Also, I noticed that you refer to your function as checkValue in main, that's probably not what you intended.

  4. #19
    Registered User
    Join Date
    May 2010
    Posts
    35
    Quote Originally Posted by tabstop View Post
    Dude. I don't know why you haven't figured this out with all the capitals and the italics.

    If you type "char" in your program IT DOES NOT MEAN STRING. STOP STOP STOP STOP and think for, yes, two minutes. DO NOT USE CHAR. Do not come back until you have something other than a char in your program.
    Obviously I'm stupid. I guess that's why I haven't figured it out yet. If I can't use char for an array to represent a string, what else can I use?

  5. #20
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by fxtdr79 View Post
    Here is my new code based on all the suggestions. Obviously I'm too stupid to figure this out. Since it should take 2 minutes and its taken me way too long.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    void checkString(char c);
    
    int main()
    {
       char c[50];
       fgets(c, 50, stdin);
    
       while (c != EOF)
       {
          checkValue(c);
          c = getchar();
       }
       return(0);
    }
    
    void checkString(char *c)
    {
       char *ptr_to_string = malloc(sizeof(char) * 100);
       strcpy(ptr_to_string, *c);
       char *find = strstr(ptr_to_string, "lb");
       if (*find != null)
       {
          puts("Input contains lb");
       }
    }
    First of all you are not stupid! You are just frustrated, relax, you will feel better once this works, because it will be YOUR WORK NOT MINE. I meant it should take two minutes to make some changes and post it back, which is what you did in that exact time frame. Take a deep breath, let the anger out, relax!

    Now back to work:

    A few things to fix now so you have a clean framework:

    1) Do you see the checkString function declaration above the main() function? It still has the old argument type char c instead of char *c. That is basically telling main: "Hey if you see checkString anywhere this is what it should look like and its argument should pe a pointer. So if you leave it as it is the compiler will give you the same warning you got before basically saying : "hey, you told me this is supposed to take a character, but you are passing the argument as a pointer! STOP DECEIVING ME!! "

    2) Delete everything in checkString and do what you were trying to do before with strstr() (not exactly sure what you were checking but you CAN NOW USE strstr, because c is now a pointer to string).

    3) Delete the while loop you have in main now. fgets actually returns NULL if it fails so what you want is to while loop like this:

    Code:
    /* read until there is nothing left */
    while(fgets(c,50,stdin) != NULL){
       /* do stuff with array c*/
    }
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  6. #21
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by fxtdr79 View Post
    Obviously I'm stupid. I guess that's why I haven't figured it out yet. If I can't use char for an array to represent a string, what else can I use?
    You've got the magic word there: array. Why not use an array to represent your string? EDIT: To be more specific, you have to change everything to be an array.
    Last edited by tabstop; 05-14-2010 at 04:21 PM.

  7. #22
    Registered User
    Join Date
    May 2010
    Posts
    35
    I changed it to the following and it works but I think it's working wrong. The documentation I'm reading is saying the 5 in fgets(c, 5, stdin) will mean at most 5 - 1 characters will be read with the result terminated with '\0'. But if I run this and type 123456789lb it tells me it found lb (or lb123456789). Shouldn't it have truncated the input and only taken 1234 in the first case, or am I using it wrong?

    Code:
    #include <stdio.h>
    #include <string.h>
    
    void checkString(char *c);
    
    int main()
    {
       char c[5];
    
       while (fgets(c, 5, stdin) != NULL)
       {
          checkString(c);
       }
       return(0);
    }
    
    void checkString(char *c)
    {
       char *cPointer;
       cPointer = strstr(c, "lb");
       if (cPointer != NULL)
       {
          puts("Input contains lb");
       }
    }

  8. #23
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    That doesn't make sense, you never print your string.

  9. #24
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    First if you want to have a string of 5 characters you should declare an array [6] to account for the '\0' as well.

    My bad. It tells you that because there is not enough space in the array. Every iteration it reads another 5 characters and replaces the ones read in the previous iteration. So on the last iteration all there is left to read is "lb" which is why that's the only thing in the array at the end.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  10. #25
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Also, notice that the while loop you are using now keeps fetching strings until you hit ctrl-c.

  11. #26
    Registered User
    Join Date
    May 2010
    Posts
    35
    Quote Originally Posted by Subsonics View Post
    That doesn't make sense, you never print your string.
    What I'm saying is if I type 123456789lb shouldn't c be c = {1, 2, 3, 4, \n} so when I call checkString, it shouldn't be able to find the string "lb"?

  12. #27
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Ah ok, claudiu mentions the reason above. fgets triggers the loop unitl the string is empty (from stdin).

  13. #28
    Registered User jephthah's Avatar
    Join Date
    May 2010
    Location
    seattle
    Posts
    49
    my god, the guy is just trying to get some string input tested and you're harassing him mercilessly and refusing to give any code like it's gold-plated or something.

    now really, if you people are going to be such hardasses, then at least get your information correct: part of the problem that he's having -- and that you're allowing to perpetuate -- is that fgets() requires you to allocate your character array by at least TWO (2) chars larger than your largest possible input, because it collects the newline ('\n') character in addition to appending the null character ('\0').

    if you're going to collect input from a user via the standard input (terminal) then you better really oversize the character buffer, unless you're prepared to develop some bulletproof error testing and input buffer overflow controls. but we're not going to go there, so for now just do it like this:

    Code:
    char c[500];                                  // yes, that's right.  memory is cheap.
    
    while (fgets(c, sizeof c, stdin) != NULL)     // no magic numbers here
    {
        checkstring(c);
    }


    Quote Originally Posted by fxtdr79 View Post
    What I'm saying is if I type 123456789lb shouldn't c be c = {1, 2, 3, 4, \n} so when I call checkString, it shouldn't be able to find the string "lb"?
    not necessarily. when you overflow your array, the behavior is undefined. depending on your system/compiler it may "work" one way or "not work" in another. looks like in this case, your overflowed char array didnt crash into anything else, so it "works". try initializing another variable before or after that array and it probably won't.




    BTW, have you considered using "strtol"? this will convert the numeric string to a (long) integer, and give back a pointer to the rest of the string. it might be a bit more useful for what you're trying to accomplish, overall. here's a lazy example that employs no error checking, just to give you an idea:

    Code:
    char str[20] = "12345 lbs";                        // notice it's "lbs" and not "lb"
    
    char *ptr;
    long value;
    
    value = strtol(str, &ptr, 10)                      // 10 is the base to convert, i.e. decimal base 10
    
    while(*ptr = ' ')                                  // is current single pointer character a space?
        ptr++;                                         // increment until it's not     
    
    if (strncmp(ptr, "lb", 2))                         // using 'strncmp' just for the hell of it.  only looks at 2 characters
        printf ('%ld pounds.\n", value);
    
    else if (strncmp(ptr, "kg", 2))
        printf ("%ld kilograms\n", value);
    
    else 
        printf ("%ld [unknown units]\n", value);
    Last edited by jephthah; 05-15-2010 at 01:27 AM.

  14. #29
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by jephthah View Post
    now really, if you people are going to be such hardasses, then at least get your information correct: part of the problem that he's having -- and that you're allowing to perpetuate -- is that fgets() requires you to allocate your character array by at least TWO (2) chars larger than your largest possible input, because it collects the newline ('\n') character in addition to appending the null character ('\0').
    No it doesn't. He's using it in a loop. It can be any size he wants. The only thing he risks is his substring being split across calls. But fgets doesn't require your input be 2 characters smaller. Fgets will read N bytes, or until it hits a newline, which ever comes first.

    Code:
    while( fgets( buf, 5, stdin ) != NULL )
    {
        ...
    }
    If the input is: 1234567, then the following will happen:

    1234\0 <-- first pass
    567\n\0 <-- second pass

    If you're going to correct people, make sure you're right.
    Quote Originally Posted by jephthah View Post
    not necessarily. when you overflow your array, the behavior is undefined. depending on your system/compiler it may "work" one way or "not work" in another. looks like in this case, your overflowed char array didnt crash into anything else, so it "works". try initializing another variable before or after that array and it probably won't.
    He's not overflowing his buffer. He's using it in a loop. The whole point of fgets is so that you can't overflow it. He's not overflowing anything. He's not right in what he thinks is going to end up in the string, but he's not overflowing it either.


    Quzah.
    Hope is the first step on the road to disappointment.

  15. #30
    Registered User jephthah's Avatar
    Join Date
    May 2010
    Location
    seattle
    Posts
    49
    on the first point, that's what i was saying. if you're expecting a 5 character input then because fgets() collects the newline, your char buffer needs to be TWO characters larger than your expected input. the fact that he's using it in a loop doesnt matter... he will have it "split across two calls" which will screw up the operation of the program.


    on the second point... yeah, you're right. he only thinks it's working because on teh second pass it finds the "lb". i must have been thinking of his previous post where he was using scanf, which would overflow. my bad.
    Last edited by jephthah; 05-15-2010 at 02:16 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Create Copies of Files
    By Kanshu in forum C++ Programming
    Replies: 13
    Last Post: 05-09-2009, 07:53 AM
  2. Quick Ques on String Manipulation
    By ckuttruff in forum C Programming
    Replies: 8
    Last Post: 06-22-2008, 09:32 PM
  3. linked list using strstr
    By ilovec.. in forum C Programming
    Replies: 3
    Last Post: 11-04-2006, 01:30 PM
  4. strstr on a wchar array
    By cloudy in forum C++ Programming
    Replies: 5
    Last Post: 06-28-2006, 06:42 AM
  5. Question about strstr()
    By choykawairicky in forum C++ Programming
    Replies: 2
    Last Post: 11-28-2004, 08:18 PM