Thread: problem entering characters in an array

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    2

    problem entering characters in an array

    I have this code that is not working and I don't understand what I am missing!
    Here is the code:
    Code:
     /*  */
      2 #include <stdio.h>
      3 #define MAX 255
      4 int main(void)
      5 {
      6         int i;
      7         char line[MAX]={0};
      8         printf("Please enter a line of text:\n");
      9         for(i=0;scanf(" %c",&line[i])!='\n';i++);
     10 
     11         printf("Now we are out of the loop!\nvalues on the array:\n");
     12         for(i=0;i!='\0';i++)
     13                 printf("%c",line[i]);
     14         printf("Bye!!!\n");
     15 
     16 return 0;
     17 }
    I enter 1 or more new lines and the program doesn't get out off of the for cicle!
    I know something is wrong but I don't know what. And I am on this for about 2 days... If somebody could help me I would be glad!
    Hugs

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Perhaps you need to find and study some documentation for scanf()?

    What do you think scanf() returns?

    When do you think the return value from scanf() will ever be equal to '\n'?

    When do you think 'c' will ever be equal to '\n'?

    Do know that the leading space in your scanf() specifier means skip leading whitespace?


    Jim

  3. #3
    Registered User
    Join Date
    May 2017
    Posts
    2
    I am not being arrogant but I know that all. The return value of scanf() obviously is 0 or 1 in this specific case. I don't have time right know, but I will return with some more explanations in order to contextualize this specific problem. See you, and manay thanks for the response.

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    The return value of scanf() obviously is 0 or 1 in this specific case.
    Well, the return result will never be '\n' as '\n' isn't equal to 0 or 1 either (proof). It doesn't make sense to compare them.
    Code:
    for(i=0;scanf(" %c",&line[i])!='\n';i++);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 12-20-2013, 05:44 PM
  2. entering characters into a string pointer
    By cfanatic in forum C Programming
    Replies: 7
    Last Post: 02-09-2013, 02:44 PM
  3. Replies: 13
    Last Post: 09-24-2008, 06:16 PM
  4. preventing user entering characters
    By Ashkan in forum C Programming
    Replies: 12
    Last Post: 08-24-2003, 12:56 PM
  5. problem with making characters in an array different colors
    By o0obruceleeo0o in forum C++ Programming
    Replies: 0
    Last Post: 04-27-2003, 12:13 PM

Tags for this Thread