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);
}
Writing each character individually using
operator<<(char)
is inefficient.Converting to an
std::string
using the(const char*, size_t)
constructor, and writing that usingoperator<<(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 withchar* name
and doesn't know its length (and there's no.length()
on it too). And yournameArray
is not initialized. Sized, yes; initialized, no. You're missing astd::copy
orstrncpy
call to copy the content offullName
intonameArray
.just works!
Start with something simple:
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
, andoperator<<
will know when to stop: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:You can even omit the size of the array, and the compiler will infer it:
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.
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.
Here's a generic way to do it.
Run example
Output: