0

I have a string as follows:

char myString[] = "Amazing String";

I want to loop over the string and print characters as follows:

int i = 0;
for (i = 0;i < sizeof(myString);i++){
    printf("%s\n", myString[i]);
}

But for some reason i get integer values instead of the character itself.

Sorry if this is a completely stupid question but i cant see what i am doing wrong.

1
  • 1
    You shouldn't use sizeof like that. Commented Jun 7, 2013 at 18:49

3 Answers 3

4

You want to use strlen() instead for the length of a string and you want to print characters (%c):

int i = 0;
for (i = 0;i < strlen(myString);i++){  // to get a string's length, use strlen
    printf("%c\n", myString[i]);       // to print a single character, use %c
}

Why use strlen() over sizeof()? Well, in this particular instance, it won't make a difference; however strlen() is for giving you the number of printable characters in a string whereas sizeof will return the size of your array (printable characters + 1 for null terminator).

int len1 = sizeof(myString); // 15
int len2 = strlen(myString); // 14

A) you won't see that printed so it doesn’t help
B) if you get in the habit of using sizeof on strings you might use it within a function you pass your array to (in which case the array will decay to a pointer) and then you'll get back the size of a char * not the number of characters at all. Same applies within the same function if you had done char *myString = "Amazing String";

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

Comments

1

You're using the "%s" symbol for strings when you should be using "%c" for single characters:

printf("%c\n", myString[i]);
//      ^^

Comments

0
int i = 0;
for (i = 0;i < sizeof(myString);i++){
    printf("%c\n", myString[i]);
}

%c instead of %s and sizeof() is not a good choice. try strlen(myString)

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.