1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Define string in C++

Discussion in 'C++' started by ballurohit, Feb 2, 2012.

  1. ballurohit

    ballurohit New Member

    Joined:
    Nov 18, 2011
    Messages:
    43
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    retired
    Location:
    Gujarat
    I want to display char string in C++.
    How it can be displayed. What is the keyword for
    displaying the char string in c++.
     
  2. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    Do you mean a c-style string?

    Code:
    char s[] = "some string";
    std::cout << s << std::endl;
    
    Note: a cstring is terminated by '\0' so that it can be used in string functions like strcmp. you can have a char array as well.

    Code:
    char char_array[] = { 'h', 'e', 'l', 'l', 'o' };
    // if you tried to output that, you may wind up with trailing junk characters.
    std::cout << char_array << std::endl;
    
    Code:
    char char_array[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
    std::cout << char_array << std::endl;
    // good to go
    
    HTH
     
  3. johnBMitchell

    johnBMitchell New Member

    Joined:
    Feb 17, 2011
    Messages:
    38
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    CA, USA
    Home Page:
    Strings are the most important part in programming .Here I give you simple example of display string.

    Suppose we use A, B, C, and D as a character
    It is initialized as followed
    Char E 1=’A’, E2=’B’, E3=’C’, E4=’D’;
    For display this char in group(string)
    Cout <<â€the string is “<<E1<<E2<<E3<<E4;
    Program for it
    #include <iostream>
    using namespace std;
    int main()
    {
    Char E 1=’A’, E2=’B’, E3=’C’, E4=’D’;
    Cout <<â€the string is : “<<E1<<E2<<E3<<E4;
    return 0;
    }

    Output of program
    The string is: ABCD
     
  4. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    That might confuse someone new to either C/C++.

    That's not a string by definition; in fact, you couldn't use it with any standard library string functions. You should also avoid using a global namespace like std - later on, it may cause problems with larger programs.
     

Share This Page