Thread: Understanding Strings - Statements

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    108

    Understanding Strings - Statements

    Hey all,

    I am having an issue here but i really don't understand what's happening. the code below asks the user to input a string and what letter does the user want to change and with what.

    The problem is that from what i see it skips entirely my for loop and statement and doesn't print anything.

    Please explain what's exactly happening and how can I fix that.

    Code:
    #include <stdio.h>
    #define MAX 100
    
    
    int main()
    {
        char str[MAX];
        char let;
        char let2;
        int i;
        
        printf("Enter String: ");
        scanf("%s", str);
        
        printf("Enter character you want to change: ");
        scanf("%s", &let);
        printf("Enter character you want to replace: ");
        scanf("%s", &let2);
        
        for (i=0; str[i]!='\0'; i++)
        {
            if (str[i] == let)
                str[i] = let2;
        }
        printf("The new string is\n%s\n", str);
        return 0;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    The variable let is a char, not a string. You cannot use %s to read a char. Try " %c" instead (notice white space).

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Do you realize that a char can only hold a single character and that the "%s" format specifier only works with C-strings, not characters.

    Also you should never use a function that doesn't limit the number of characters it will retrieve into a C-string? With the scanf() function you can use the width modifier to limit the number of characters the function will retrieve. Just be careful to leave enough room for the end of string character:
    Code:
        char str[MAX];
    ...
        printf("Enter String: ");
        scanf("%99s", str);

    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem Using Strings in IF statements
    By Programmer3922 in forum C Programming
    Replies: 6
    Last Post: 08-02-2008, 01:36 PM
  2. Using strings in if statements
    By Brittany in forum C Programming
    Replies: 5
    Last Post: 03-14-2005, 05:15 PM
  3. if statements using strings as the condition
    By trang in forum C Programming
    Replies: 7
    Last Post: 12-13-2003, 05:20 PM
  4. Switch statements for strings
    By cxs00u in forum C++ Programming
    Replies: 5
    Last Post: 04-17-2002, 03:38 PM
  5. need a little help with if statements and strings
    By kes103 in forum C Programming
    Replies: 1
    Last Post: 03-20-2002, 12:08 PM