Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

Cannot figure out how to format strings in an array (C) – very new to comp sci

I've looked through many questions here, but the syntax is unfamiliar to me. I am trying to write a program in C, that given a composer's name, will give you the instrumentation that composer used in orchestral music. I am trying to figure out how to format strings in an array, but the compiler won't recognize them. I have tried using one variable, no luck. Right now, only errors from compiler are "undeclared identifiers" for each indexed composer's name in j[0], j[1], j[2]. So far I have:

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

int main(void)
{
    printf("Henlo, (')> I will determine your average orchestral instrumentation per composer.
");
    printf("Your options are: JS_Bach, Mozart, Beethoven, Brahms, Wagner, R_Strauss, Ravel, and Debussy.
");

    string i = get_string("Composer: "); //get_string (from <cs50.h> prompts the user to enter text

    string j[8];
        j[0] = JS_Bach; //undeclared identifiers for j[0] thru j[7]
        j[1] = Mozart;
        j[2] = Beethoven;
        j[3] = Brahms;
        j[4] = Wagner;
        j[5] = R_Strauss;
        j[7] = Ravel;
        j[7] = Debussy;

    if (i == j[0])
    {
        printf("2fl, 2-3ob, maybe d'amore/da caccia, 3trp, timp, vln.I, vln.II, vla, SATB choir + solo, bc
");
    }
    else if (i == j[1])
    {
        printf("1-2fl, 2ob, maybe 2cl/basset 2bsn, 2hrn, 2trp, timp, vln.I, vln.II, vla, vlc, cb
");

//same format with different text in printf for j[2] thru j[7], (won't waste space here with the rest)

I have also seen questions with code using char** and things like that; could someone explain the asterisk's purpose? Do I need to declare items as char instead of string? The type string is defined by <cs50.h>. Not sure if I will need another function library to use strings in arrays?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are referring to the names as identifiers and not as constants like you want them to be. Change Wagner to "Wagner" for example. You get an error because these identifiers were never defined before being used by you.

Also, right now when you are comparing the strings you are comparing their addresses in memory. Consider using strcmp if you want to compare the strings and not their addresses.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...