-4
void character(){
int i=0;
char c;
printf("type your text to encode (max 80 chars):\n");
while((c=getchar()) != '\n')
{
    text[i] = toupper(c);
    i++;
}
text[i] = '\0';}

I'm using this piece of code in an emulator of Enigma. My problem is that the While instruction is always jumped, and I can't understand what's the problem and how to fix it!

  • 1
    Where is `text` declared? – CloudPotato Jan 19 '17 at 17:08
  • 1
    Are you reading anything from the user before this point? If before calling `character()` you read something with `scanf`, it might have left a newline in the input stream. – trent Jan 19 '17 at 17:08
  • 1
    Fyi, `c` should be `int`. Second since this code can't possibly compile as-posted, much less run to reproduce the problem you're describing, the mystery is shared by all of us. Update your post with a [minimal, **complete**, verifiable example](https://stackoverflow.com/help/mcve) that reproduces your problem, including any input requirements – WhozCraig Jan 19 '17 at 17:09
  • Okay, after adding `char text[80];` I can't reproduce your issue. – DeiDei Jan 19 '17 at 17:10
  • Agreed on the type of `c`, and read this Q&A to understand better why: http://stackoverflow.com/questions/35356322/difference-between-int-and-char-in-getchar-fgetc-and-putchar-fputc – trent Jan 19 '17 at 17:10
  • You do know that [`getchar`](http://en.cppreference.com/w/c/io/getchar) will return `EOF` on error or end-of-file? And that `EOF != '\n'`? – Some programmer dude Jan 19 '17 at 17:11
  • `text` is declared outside, and also using `c` as an `int` I've got the same problem. – Nicola Giardino Jan 19 '17 at 17:26

2 Answers2

1

Maybe there is something wrong with the declaration of the array text. This solution could clarify your question.

#include <stdio.h>
#include <ctype.h>

#define MAX_SIZE 10

int main(void) {
  char text[MAX_SIZE];
  int i = 0;
  int c;

  while ((c = getchar()) != '\n' && i <= MAX_SIZE - 2) {
    text[i] = toupper(c);
    i++;
  }
  text[i] = '\0';

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

  return 0;
}
Modfoo
  • 97
  • 9
0

As @trentcl mentioned, if there is a scanf prior to calling character() there is probably a newline left in the input stream. This will test for a leading newline and continue the loop.
The #define will set the size of the array so the loop does not put too many characters into text.

#define LIMIT 256
char text[LIMIT + 1] = {'\0'};

void character(){
    int i = 0;
    int c;
    printf ( "type your text to encode (max 80 chars):\n");
    while ( ( c = getchar ( )) != EOF)
    {
        if c == '\n') {
            if ( i) {
                break;//trailing newline
            }
            else {
                continue;//leading newline
            }
        }
        text[i] = toupper ( c);
        i++;
        if ( i >= LIMIT) {
            break;
        }
    }
    text[i] = '\0';
}
xing
  • 2,125
  • 2
  • 14
  • 10