Thread: Passing C++ strings

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    9

    Passing C++ strings

    Just a quick question, is it possible to pass C++ strings from main into a function. May sound simple but it's not working for me.

    Also does anyone know of a good tutorial on writing to and reading from a .txt file.

    Thanks for your help.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    You mean something like this:
    Code:
    #include <string>
    #include <iostream>
    
    void func(std::string str)
    {
        std::cout <<  str << std::endl;
    }
    
    int main()
    {
        std::string str = "Hello World";
    
        func(str);
    
    }
    Output:
    Code:
    Hello World
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You mean something like this:
    Code:
    #include <string>
    #include <iostream>
     
    void func(const std::string& str)
    {
    	std::cout << str << std::endl;
    }
     
    int main()
    {
    	std::string str = "Hello World";
     
    	func(str); 
    }
    As you probably know, I think the string class is complex enough to pass a const reference instead of making a copy.

  4. #4
    Registered User
    Join Date
    Nov 2003
    Posts
    9

    Thanks for your help

    Thanks for your input on this, they have both helped me in my functions, sorry to be so vague but the prob is i'm only starting my development and very little to offre by way of concrete code.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing Array of Strings to a function ??
    By Taper in forum C Programming
    Replies: 20
    Last Post: 12-07-2008, 02:58 PM
  2. Passing strings to functions and modifying them
    By diddy02 in forum C Programming
    Replies: 6
    Last Post: 08-11-2008, 01:07 AM
  3. passing strings from functions as the "return" part
    By fraktal in forum C Programming
    Replies: 8
    Last Post: 12-13-2005, 01:38 AM
  4. Passing an Array of Strings from VB to a C DLL
    By mr_nice! in forum Windows Programming
    Replies: 9
    Last Post: 03-08-2005, 06:16 AM
  5. Passing Strings by Reference
    By xshapirox in forum C++ Programming
    Replies: 3
    Last Post: 10-11-2004, 09:35 AM