declaring string

Discussion in 'Programmer's Corner' started by TAKYMOUNIR, Dec 1, 2012.

  1. TAKYMOUNIR

    Thread Starter Active Member

    Jun 23, 2008
    351
    1
    this program i see in text book and i try to compile it but it does not work ,it does not except string ,i get error say that string not declared so what is the wrong i use gcc compiler
    Code ( (Unknown Language)):
    1. #include <stdio.h>
    2. #include<string.h>
    3. int main( void )
    4. {
    5. string s[4] = {"hello", "help", "save me", "groan"};
    6. char t[] = "help";
    7. string p = s[3];
    8. printf( "%4s?\n", s[0] );
    9. printf( "%s! ", p );
    10. printf( "%10s ", s[2] );
    11. printf( "%i", t == s[1] );
    12. printf( "%c!\n", s[0][0] );
    13. }
    14.  
     
  2. tshuck

    Well-Known Member

    Oct 18, 2012
    3,531
    675
    You need to specify what namespace 'string' lies in... either write 'std::string' for each instance of string, or 'using namepsace std;' toward the top outside of main()..... also, depending on your compiler, you may get an error in printing a string with printf(I'm not familiar with gcc...), you may need to convert the string to a char*, you can use s.c_str() to convert to a const char*...
     
  3. takao21203

    Distinguished Member

    Apr 28, 2012
    3,577
    463
    string p = s[3];

    I don't think this can work.
    You need to use some kind of strcpy.

    It is really called strcpy but of course, does string copy.
     
  4. spinnaker

    AAC Fanatic!

    Oct 29, 2009
    4,866
    988

    Also the wrong include file at the top

    #include <string>

    not


    #include <string.h>
     
  5. tshuck

    Well-Known Member

    Oct 18, 2012
    3,531
    675
     
  6. WBahn

    Moderator

    Mar 31, 2012
    17,716
    4,788
    I don't see anything that states whether this is C or C++. What is the extension on your source code file, .c or .cpp? Some compilers (don't know about gcc) use this to determine whether to assume it is C or C++ and configure the compiler options accordingly.

    If it is being compiled as a C program, the there is not variable type called "string".
     
Loading...