You are not logged in.

#1 2013-07-21 20:17:16

cris9288
Member
Registered: 2013-01-07
Posts: 348

[solved] extra character at end of C program

I'm trying to shake off some C rust, but there's something that's annoying me. I wrote a small program to illustrate what's going on.

 2:13 PM ~/code/c % ./string 
hello world.
hello world.%  

that percent sign (black fg, white bg btw) appears at the end of my program and I can't tell if it's something that I'm doing wrong (most likely it is).

here's my code

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define INIT_SIZE 32

void strinput(char *str, int char_limit);
int expand_buffer(char *buffer, int old_size);


int main() {

    int buffer_size;
    int ndx; 
    char *input;

    buffer_size = sizeof(char) * INIT_SIZE;
    input = (char *) malloc(buffer_size);

    strinput(input, buffer_size);

    printf("%s", input);


    return 0;

}

void strinput(char *str, int char_limit) {

    int ndx = 0;

    while((str[ndx] = getchar()) != '\n') {
        if(++ndx == char_limit)
            char_limit = expand_buffer(str, char_limit);
    } 

    str[ndx] = '\0';

}

int expand_buffer(char *buffer, int old_size) {

    old_size += (sizeof(char) * old_size);

    buffer = (char *) realloc(buffer, old_size);

   return old_size;

}

This character appears in urxvt and xfce4-terminal. Any ideas?

Last edited by cris9288 (2013-07-21 21:32:02)

Offline

#2 2013-07-21 20:31:11

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: [solved] extra character at end of C program

That's your prompt. You use '%' for your prompt.
I got

[foo]$ ./string
hello world
hello world[foo]$ 

You should include a carrier carriage return.

Last edited by karol (2013-07-21 20:38:18)

Offline

#3 2013-07-21 20:31:43

WorMzy
Administrator
From: Scotland
Registered: 2010-06-16
Posts: 12,600
Website

Re: [solved] extra character at end of C program

Add a \n at the end of your printf string.


Sakura:-
Mobo: MSI MAG X570S TORPEDO MAX // Processor: AMD Ryzen 9 5950X @4.9GHz // GFX: AMD Radeon RX 5700 XT // RAM: 32GB (4x 8GB) Corsair DDR4 (@ 3000MHz) // Storage: 1x 3TB HDD, 6x 1TB SSD, 2x 120GB SSD, 1x 275GB M2 SSD

Making lemonade from lemons since 2015.

Offline

#4 2013-07-21 20:47:32

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: [solved] extra character at end of C program

WorMzy,is right, it has to be a newline, because a carriage return does this:

[foo]$ ./t
hello world
[foo]$ orld

;P

Offline

#5 2013-07-21 21:31:39

cris9288
Member
Registered: 2013-01-07
Posts: 348

Re: [solved] extra character at end of C program

I am an idiot. You guys are right.

Offline

#6 2013-07-22 13:04:38

Stalafin
Member
From: Berlin, Germany
Registered: 2007-10-26
Posts: 617

Re: [solved] extra character at end of C program

That was hilarious. Thanks for the laugh! smile

Offline

Board footer

Powered by FluxBB