4 Replies - 747 Views - Last Post: 08 March 2018 - 06:59 PM Rate Topic: -----

#1 leodavinci1990   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 07-March 18

Enqiry about cout for a char type

Posted 07 March 2018 - 05:57 AM

Third cout statement prints two Hello instead of one!!!

#include <iostream>
#include <string>
using namespace std;
//Ctrl+Shift+C to comment
//Ctrl+Shift+X to uncomment

int main()
{
    char foo[] = "Hello";
    char bar[] = "World!";
    char foo1[6] = "Hello";
    char myword[5] = {'H','e','l','l','o'};
    //char once initialized cannot be assigned values (again)
    cout<<foo<<endl;
    cout<<bar[0]<<endl;
    cout<<myword<<endl;
    cout<<myword[0]<<endl;

    cout<<sizeof(foo)<<endl;
    cout<<sizeof(foo1)<<endl;

    string monkey ("My name is");
    string house ("Mohammad");
    string monkeys = monkey +" " + house;   //Try concatenation
    cout<<monkeys<<endl;

    return 0;
}

:code:

This post has been edited by modi123_1: 07 March 2018 - 06:31 AM
Reason for edit:: fixed botched code tags


Is This A Good Question/Topic? 0
  • +

Replies To: Enqiry about cout for a char type

#2 jimblumberg   User is online

  • member icon

Reputation: 5487
  • View blog
  • Posts: 17,063
  • Joined: 25-December 09

Re: Enqiry about cout for a char type

Posted 07 March 2018 - 06:21 AM

Well you can't print an array of char with the insertion operator<<, you'll either need to print each individual element of the array (with a loop) or increase the array size by one and add the end of string character to make the array a C-string.

Edit: Also here.


Jim

This post has been edited by jimblumberg: 07 March 2018 - 06:21 AM

Was This Post Helpful? 0
  • +
  • -

#3 leodavinci1990   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 07-March 18

Re: Enqiry about cout for a char type

Posted 07 March 2018 - 06:27 AM

Hi Jim,
Thanks for you reply.
What do you mean by "increase the array size by one and add the end of string character to make the array a C-string"? Can you provide an example.
Thanks
Was This Post Helpful? 0
  • +
  • -

#4 jimblumberg   User is online

  • member icon

Reputation: 5487
  • View blog
  • Posts: 17,063
  • Joined: 25-December 09

Re: Enqiry about cout for a char type

Posted 07 March 2018 - 10:10 AM

Quote

Can you provide an example.

I suggest you do some research to find the differences between an array of char and a C-string.


Jim
Was This Post Helpful? 1
  • +
  • -

#5 femrost   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 09-January 18

Re: Enqiry about cout for a char type

Posted 08 March 2018 - 06:59 PM

do you need to use char's? if not i would suggest using string's.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1