0

So, while working on the "initials" problem this kind of error appeared after I thought I've finished with my code.

error: array initializer must be an initializer list

I'm posting my whole code and hope any of you guys can explain to me what that error means and gives me a tip on how to solve it.

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

int main(void)
{   
    string s[] = GetString();

    for(int i = 0, k = strlen(s); i < k; i++)
    {
        for(int n = 0; n <= i; n++)
        {
            int j = 0;

            if(s[i][j] >= 'a' && s[i][j] <= 'z')
            {    
                printf("%c\n", s[i][j]) - ('a' - 'A');
            }
            else
            {
                printf("%c\n", s[i][j])
            }
        }
    }
}

1 Answer 1

3

When you have square brackets following the name of a variable, the compiler thinks that you are trying to declare an array of type string with name "s". But that isn't what you want to do with this. The whole name (with spaces) will be stored in that variable and what you want to do is parse the string and essentially print the initials. To do this, you should lose the square brackets on the declaration of "s" and omit "[j]" because you are parsing through the chars of a single string.

What I'm confused about is that when I run the fixed code it doesn't quite do what it's intended to. The output looks like this:

~/workspace $ ./test
Rick Astley
R
I
I
C
C
C
K
K
K
K





A
A
A
A
A
A
S
S
S
S
S
S
S
T
T
T
T
T
T
T
T
L
L
L
L
L
L
L
L
L
E
E
E
E
E
E
E
E
E
E
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
~/workspace $

Was this an intended feature? The CS50 Initials I know of runs more like this:

~/workspace/pset2 $ ./initials
Zamyla Chan
ZC
~/workspace/pset2 $ ./initials
robert thomas bowden
RTB

If not then I would also advise the removal of an extra for loop.

EDIT: To print a char directly after the space and capitalize it in one go, shove this if statement in a for loop. (ctype.h library)

if (name[i] == ' ')
{
    printf("%c", toupper(name[i + 1]));
}
3
  • 1
    Yup! Also, remove the extraneous \n if you don't want to print all those newlines. Aug 1, 2016 at 5:28
  • But I delibarately want to use an array of strings, because otherwise how would I tell my program that I want it to use just the first letter after the "space", if not telling it that there is another string and I want to use just its first character. Aug 1, 2016 at 10:12
  • Well since a string is just an array of chars, you can parse that array and once you find a space you can print the char that comes directly after it. Check my answer edit. Aug 1, 2016 at 15:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .