0

I'm trying to read a constant length string as an array of c for 8 times. Each time i override the content of the previously read array.

The code seems to be working at the first loop cycle, but then as you can see below, I get some weird output. What am I missing?

CODE:

#include <stdio.h>

#define MAX_READ_CYCLES 8
#define MAX_STRING_LENGTH 4

int main(){

  int i, cycles;
  char a[MAX_STRING_LENGTH+1];


  /***************************************************
   * BEGIN Read logic
   ***************************************************/

  for(cycles=0; cycles < MAX_READ_CYCLES; cycles++){

    i=0;

    printf("\nEnter a string: ");

    while(i < MAX_STRING_LENGTH){
      a[i] = getc(stdin);
      i++;
    }

    a[i] = '\0'; //string end character

    fflush(stdin); //cleaning the buffer

    printf("String you entered: %s\n", a);

  }

  /***************************************************
   * END
   ***************************************************/


   return 0;
}

OUTPUT:

Enter a string: cccc
String you entered: cccc

Enter a string: cccc
String you entered: 
ccc

Enter a string: String you entered: 

Enter a string: 
7
  • 1
    What happens if you enter abcd and then efgh for the first two inputs? Commented Dec 21, 2015 at 1:03
  • Allocating memory during run time requires dynamic memory allocation Commented Dec 21, 2015 at 1:04
  • @ScottHunter: the output is the same, the first cycle i get abcd on the same line correctly. The second one just efg on a new line. Commented Dec 21, 2015 at 1:05
  • What could cause both the second output to miss the last character it should show and start on a new line, even though the program prints 4 distinct characters? Commented Dec 21, 2015 at 1:10
  • 1
    fflush(stdin) is not guaranteed to do what you want. It's undefined behaviour on some platforms and unpredictable at best even on those platforms which define it (Linux). On Linux it flushes already read data that has been buffered but not unread data. So your input stream still contains the new line characters which you need to account for. Suggest using fgets instead. Commented Dec 21, 2015 at 1:13

3 Answers 3

3

fflush(stdin); causes undefined behaviour. Replace that line with:

int ch;
while ( (ch = getchar()) != '\n' && ch != EOF ) {}

Your code has another logical issue. It always reads 4 characters , even if the person presses Enter first. So if someone types hi and presses Enter then it keeps waiting until the next Enter press.

You may want to modify the while loop to also break if the key '\n' was just entered. In this scenario you would NOT go on to clean the input as described above.

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

1 Comment

Even better: While loop to also break if the int "key" '\n'` or EOF.
1

Consider a few issues:

a[i] = getc(stdin); would take the previous Enter as an input, and so you'd loose one character.

You can try scanf( " %c", &a[i] ); instead, which would eliminate the buffered Enter character, and also the need for fflush() function.

In your case, it might not be necessary, but usually I'd reset the character array before each read iteration using memset:

memset( a, 0, sizeof( a ) ); // this requires <string.h>


Enter a string: cccc
String you entered: cccc

Enter a string: cccc
String you entered: 
ccc    # one `c` is missing because the input buffer looks like this `<Enter>cccc`, in which `<Enter>` is left over from previous input.

Enter a string: 

String you entered: c # display `c` because input buffer contains `c<Enter><Enter><Enter>`, in which `c<Enter>` is left over from previous input.

2 Comments

Thank you for your reply, scanf() is working like expected. One thing I noticed is that to work correctly it's important the space before the %c. Is that necessary to force the buffer to reset?
Yes, always add a space in scanf( " %c", &c ); to make sure space characters like Enter is not interpreted as real input.
0

Your code segment reads in exactly four characters including newlines. Use the scanf() library function to input string characters into a

#include <stdio.h>

#define MAX_READ_CYCLES 8
#define MAX_STRING_LENGTH 4

int main(){

  int i, cycles;
  char a[MAX_STRING_LENGTH+1];


  /***************************************************
   * BEGIN Read logic
   ***************************************************/

  for(cycles=0; cycles < MAX_READ_CYCLES; cycles++){

    i=0;

    printf("\nEnter a string: ");

    scanf("%s", a);

    fflush(stdin); //cleaning the buffer

    printf("String you entered: %s\n", a);

  }

  /***************************************************
   * END
   ***************************************************/


   return 0;
}

3 Comments

Thanks for your answer but I want to use char arrays instead of strings, so scanf() with a string would not fit my needs.
In c the two are identical with the caveat that a string is null-terminated. Do you mean you have to populate your character array character by character?
Exactly, i need to populate the array character by character.

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.