-1

I'm reading the BigNerdRanch book on Objective-C and it's running me through how to take lines into stdin in regular C. For some reason, the example code that's supposed to run with readline duplicating input (small bug) is not functioning. It builds successfully but after taking input in which if I type Mikey it displays MMiikkeeyy,

I get:

(lldb) IMPLICIT DECLARATION OF FUNCTION READLINE IS Thread1:EXC_BAD_ACCESS(code=1,address=0x20000)

Code:

#include <stdio.h>

int main(int argc, const char * argv[])
{
    printf("Who is cool? ");
    const char *name = readline(NULL);
    printf("%s is cool!\n\n", name);
    return 0;
}

Any help is much appreciated.

tijko
  • 7,599
  • 11
  • 44
  • 64
steviesh
  • 1,740
  • 6
  • 19
  • 33

3 Answers3

1

You did not include the header file where readline() is declared. Therefore the compiler assumes that the function returns int. This is the reason for the crash at runtime.

If you use the GNU readline library then add

#include <readline/readline.h>
#include <readline/history.h>

to your code. But from your question I assume that you are compiling with Xcode on OS X. OS X has a "libedit" library which has a "readline wrapper". In that case you only include

#include <editline/readline.h>

The duplicate input (MMiikkeeyy) is probably a problem of the debugger console. It should work correctly if you start your program from the command line.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0
#include <stdio.h>

int main(int argc, const char * argv[])
{
    printf("Who is cool? ");
    char name[50];
    scanf("%s",name);
    printf("%s is cool!\n\n", name);
    return 0;
}

The code above does what you desire.

There were two problems with your code

  1. There is no function called readline. the function that reads characters from standard input is called scanf. the Function takes 2 parameters a format like %s which means you want to read a string of characters and the variable you want to store the characters in.
  2. There was also a problem with your variable definition. You have do declare it as an array with [size] after the name so you can store more than one character.

Hope this helps and for a good c resource see here

06needhamt
  • 1,555
  • 2
  • 19
  • 38
0

For me when compiling to inclue readline, the include's weren't enough:

#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>

I had to link to readline:

gcc readline_prog.c -o readline_prog -g -Wall -Wextra -lreadline

As mentioned here some may need to provide additional paths to the compiler aswell.

Community
  • 1
  • 1
tijko
  • 7,599
  • 11
  • 44
  • 64