0

My goal is to make a program that would scan a word from input and then save it into one large string.

I know for sure that input is always word '\n' word '\n' ...

So I'm trying to scan a single character and save it into an array and replace '\n' with ' '.

My code:

char c;
char *line;
int len = 0;

while(!feof(stdin))
{
    len++;
    char *line = (char *)malloc(sizeof(char) * len);
    scanf("%c", &c);
    if (c == '\n')
        line[len - 1] = ' ';
    else
        line[len - 1] = c;
}

int q;
for(q = 0; q < len - 1; q++)
    printf("%c", line[q]);

Ouput is error. (RUN FAILED (exit value 1, total time: 2s)

For example I want for input :

one
two
three
four
five

and this for output:

"one two three four five"
Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
Pastx
  • 687
  • 3
  • 8
  • 23
  • Please provide more details about the precise error you’re receiving as output. – Benjamin Barenblat Dec 01 '13 at 20:49
  • Maybe have a look at http://stackoverflow.com/questions/2532425/read-line-from-file-without-knowing-the-line-length – kajacx Dec 01 '13 at 20:50
  • 4
    Nonononono. Just leave poor `scanf()` alone. You don't need it. You don't want to use it. You want **sane, secure, easy to use** functions, such as `getchar()` or `fgets()`. You also absolutely do not want to cast the return value of `malloc()`. –  Dec 01 '13 at 20:51

2 Answers2

0

Each time around your while loop, you allocate a new line, throwing away the old value and the characters in it. You never initialize anything except the last character, so when your loop finishes, line is garbage, except for the last character. You want to just allocate a large enough buffer ONCE at the start, or use realloc to make the buffer larger.

You have while(feof(stdin)) which is pretty much always wrong -- feof is only true AFTER failing to read a character from the input. So you end up looping one too many times, duplicating the final character. Check the return value of scanf instead.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
0

I made this based on your responses.

char c;
char *line;
int len = 0;

while (scanf("%c", &c) != EOF) {
    len++;
    line = (char *) realloc(line, sizeof (char) * len);
    if (c == '\n')
        line[len - 1] = ' ';
    else
        line[len - 1] = c;
}
Pastx
  • 687
  • 3
  • 8
  • 23