0

I am currently taking a basic C course and I was wondering why my code below doesn't run.

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

int main()
{ 
    char string[4];

    printf("Enter some text\n");
    scanf(" %c %c %c", &string[0], &string[1], &string[2]);

    printf("You Entered ");

    int i;
    for (i = 0; i < 4; i++){
        printf("%c",string[i]);
    }

    return 0;
}

Xcode said there is an errr with my scanf line.

I was hoping to type in "a b c d" and expect a "You entered abcd";

8
  • 1
    What error did it say specifically? Commented Feb 20, 2014 at 19:30
  • "(lldb)" "error: 'apropos' must be called with exactly one argument." Commented Feb 20, 2014 at 19:31
  • Did you type make or man to build? Commented Feb 20, 2014 at 19:33
  • Based on that error, why do you think the problem is with the scanf line? Commented Feb 20, 2014 at 19:34
  • I used Xcode to go to Product>Run if that helps. Also, I not sure what that error is saying, especially the apropos part. Commented Feb 20, 2014 at 19:39

2 Answers 2

1

This code should run (albeit with a bug). I suspect you need to configure the Xcode build options correctly.

As for the bug, you have an array of four chars, but you are only scanning for three. Add another %c and &string[3] to your scanf line.

Here's an ideone snippet showing the modified code in action

#include <stdio.h>

int main()
{ 
    char string[4];
    int i;

    printf("Enter some text\n");
    scanf("%c %c %c %c", &string[0], &string[1], &string[2], &string[3]);

    printf("You Entered ");

    for (i = 0; i < 4; i++){
        printf("%c", string[i]);
    }

    return 0;
}

This compiles just fine on the Mac command line (assuming the source is in "test.c")

$ cc -g -Wall -o test test.c 
./test
Enter some text
a b c d
You Entered abcd

Also note that this particular snippet requires only stdio.h (man scanf and man printf will tell you which header to use).

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

Comments

0

How about executing this code?

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

int main()
{ 
    char strin[10];

    printf("Enter some text\n");
    scanf("%s", strin);

    printf("You Entered %s",strin);

    return 0;
}

The following code gives you :

Enter some text
abcd
You Entered abcd

enter image description here

Comments

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.