Chandy
Chandy

Reputation: 161

Using cout to print the entire contents of a character array

I am quite new to C++ (just a shaky background in Java) and I'm stumped about how to print out the entire contents of a char array. I believe I need to use a loop, and base the loop on the length of the array, but my attempts to compile aren't meeting with success. This is what I have right now. Thanks in advance for your help!

#include <iostream>
#include <string>

using namespace std;

void namePrinting(char name[])
{
   int i = 0;
   cout << "Name: ";
   while(i <= name.length() )
   {
   cout << name[i];
   i++;
   }

}

int main()
{
   string fullName;
   cout << "Enter name: ";
   cin >> fullName;
   char nameArray[fullName.length()];
   namePrinting(nameArray);
}

Upvotes: 15

Views: 107598

Answers (6)

yano
yano

Reputation: 5265

This is a bit <O/T> from the OP, but I googled "c++ print std::array char" and this was the top hit, yet none of these answers cover how to do this with std::array<char, >. You can't apply the operator<< directly to the array, you need to access its .data() pointer first:

#include <string>
#include <iostream>
#include <array>
 
int main()
{
  // a direct initialization example. Remember, need string legnth+1 for
  // a NUL terminator
  std::array<char, 6> bar{"hello"};
  // print to std::out using operator<< and the .data() ptr access
  std::cout << bar.data() << std::endl;

  // extra example copying the contents of a string to an array.
  std::string foo("how are you?");
  // {} initializes it to 0, giving us guaranteed NUL termination
  std::array<char, 24> tar{};
  // copy string to array, std::min ensures we won't overrun
  foo.copy(tar.data(), std::min(foo.length(), tar.size()-1));
  std::cout << tar.data() << std::endl;

  return 0;
}

Output:

hello
how are you?

Demonstration

Upvotes: 0

ppetraki
ppetraki

Reputation: 428

Here's a generic way to do it.

Run example

// write out any c style char array to an output stream
#include <iostream>

#include <string.h>

void write_char_array(std::ostream& os, const char* string) {
    // faster than an ostream_iterator and std::copy
    os.write(string, strlen(string));
}

int main()
{
    const char question[] = "What is your name? ";
    const char* answer    = "Bob";

    write_char_array(std::cout, question);
    write_char_array(std::cout, answer);
}

Output:

What is your name? Bob

Upvotes: 0

James Yen
James Yen

Reputation: 61

For my problem, my program was looking for a command line parameter. Since I did not provide the parameter, so it throws terminate called after throwing an instance of std::logic_error what(): basic_string::_S_construct null not valid

I hope this gives you some insight on how to figure your problem.

Upvotes: 0

Al2O3
Al2O3

Reputation: 3203

printf("%s", nameArray);

just works!

Upvotes: 3

ddevienne
ddevienne

Reputation: 1882

Writing each character individually using operator<<(char) is inefficient.

Converting to an std::string using the (const char*, size_t) constructor, and writing that using operator<<(const std::string&) is also inefficient.

The proper way is simply to use http://en.cppreference.com/w/cpp/io/basic_ostream/write

PS: Note that your code is not valid C++. char name[] is basically synonymous with char* name and doesn't know its length (and there's no .length() on it too). And your nameArray is not initialized. Sized, yes; initialized, no. You're missing a std::copy or strncpy call to copy the content of fullName into nameArray.

Upvotes: 4

Beta
Beta

Reputation: 99084

Start with something simple:

char c_array[3];
c_array[0] = 'a';
c_array[1] = 'b';
c_array[2] = 'c';

for(int i=0 ; i<3 ; ++i)
{
  cout << c_array[i];
}
cout << endl;

Do not go farther until you understand that much perfectly. Now notice that if you null-terminate the array, you can pass the whole thing to cout, and operator<< will know when to stop:

char c_array[4];
c_array[0] = 'a';
c_array[1] = 'b';
c_array[2] = 'c';
c_array[3] = 0;

cout << c_array << endl;

You cannot do that with arrays of most other types. Now notice that you can assign a char[] this way, and it will be null-terminated:

char c_array[20] = "abc";
cout << c_array << endl;

You can even omit the size of the array, and the compiler will infer it:

char c_array[] = "abc";    // this is a char[4];
cout << c_array << endl;

There are a couple of different ways to read user input into an array, but it sounds as if you know that already, and this answer is getting long.

Upvotes: 31

Related Questions