0

I am trying to print array of characters in C, but the array is not printing if any blank space occurs. This is my code:

int main() {
    char str[100];
    int len = 0;

    printf("Enter the string");
    scanf("%s", str);
    len = strlen(str);

    int i = 0;
    for (i = 0; i < len; i++) { 
       printf("%s", str[i]); 
    }    

    getch();
}

Input: Bangalore is in India
Output: Bangalore

Any suggestions?

5
  • %c is what you want, not %s Commented Apr 5, 2014 at 2:38
  • 1
    %s is the format specifier for a string. You are trying to print one character at a time (str[i]). So you should either, just once, do printf("%s\n", str); or, in your loop, do printf("%c", str[i]); and follow that with printf("\n"); (newline string) or putch('\n'); (newline char). Commented Apr 5, 2014 at 2:39
  • 5
    Also, scanf stops at the space. Commented Apr 5, 2014 at 2:39
  • This probably isn't that relevant but have you considered using fgets instead? Commented Apr 5, 2014 at 2:43
  • It is not working with %c ... It is printing the same Commented Apr 5, 2014 at 2:49

3 Answers 3

5

With scanf() , the %s format skips leading white space, then scans non-white space characters and stops at the next white space in the input line.

That means that only Bangalore is read, so only Bangalore is printed.

If you want a whole line of input, you should probably use fgets().

You should also be getting warnings from your compiler about your printing code. You probably want to use this without a loop:

printf("%s\n", str);

or this within a loop:

printf("%c", str[i]);

though this would be faster:

putchar(str[i]);

and you would need to worry about adding a newline at the end (putchar('\n'); after the loop).

Sign up to request clarification or add additional context in comments.

2 Comments

Even this would print only bangalore .... I want the whole string to be printed...
To read in the whole string rather than just Bangalore, you have to read the whole string. Like I said, you need to use fgets() unless you want to use " %99[^\n]" instead of "%s" in your scanf call. It is fiendishly difficult to use scanf() and its relatives correctly. They're seductively simple on the surface, but horribly complex once you start getting down to real business with them.
1

Reading input from terminal would stop if it encountered a space or a new line. You could do 2 things to get what you need

  1. Use fgets, ex : fgets(str, 100, stdin)
  2. Tell scanf to read input while it's not a newline like this scanf ("%[^\n]%*c", str);

and the second thing,if you are printing out character arrays, you must use %c

Comments

0

Read the manual pages

you need %c not %s

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.