char arr[5];
cout << "Enter ZipCode: \n>";
for (int i = 0; i < 5; i++)
cin >> arr[i];
cout << arr << endl;
im trying to put a user input zipcode into a char array, but whenever I print the array, it prints the zipcode fine, but places all of this ascii nonsense behind it.
its a full line of this ascii nonsense, why would a character array print that? what i do wrong?
why would a character array print that? what i do wrong?
You probably forgot to save room for, and to add, the end of string character.
Why are you using an array of char instead of a C++ string? The C++ string is much safer to use and is dynamic, meaning you don't need to worry about it's size.
And lastly why are you trying to get individual characters instead of retrieving a string?
Character arrays are normally terminated by '\0'. Since you don't have it it prints more characters.
To fix it you can print each character separate or you add it at the end but then you need to make your arr one longer.
That won't solve the problem. std::string is going to try and determine the length of the string by scanning for the null terminator. If there isn't one, it will keep scanning until it finds a byte contaning binary zero.
Hi AbstractionAnon, thanks for your feedback, would you try this snippet please, it seems that string handles this cast in Visual C++ 2010 and cplusplus.com shell :
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <string>
usingnamespace std;
int main(){
char arr[5];
cout << "Enter ZipCode: \n>";
for (int i = 0; i < 5; i++)
cin >> arr[i];
string s = (string)arr;
cout << s.length() << endl;
cout << s << endl;
}
Hi AbstractionAnon, thanks for you feedback.
I tried this snippet in Code::Blocks, and yes it outputs something like what you get. But in Visual C++ and CPlusPlus.com Shell it works great. What is your compiler ? What the ISO says about this ?
output in cplusplus.com Shell and Visual C++2010
Just because Visual C++ works as you expect, this time, doesn't mean it will always work. Trying to use an unterminated array of char as a C-string will produce Undefined Behavior. One of the hazards of undefined behavior is that you never know what will happen. Sometimes it will work as expected other times is will fail spectacularly. Many times just adding a few more bits of code, changing compile options, or a host of other things can affect the program output.