Reputation: 339
i'm trying to pass a char[] to another function, but for some reason I keep getting weird outputs but have no errors. I have the following methods:
void storeKey()
{
char keyArray[10];
cout << "Please enter 10bit key" << endl << "==> ";
cin >> keyArray;
storePlaintext(keyArray);
cout << keyArray << endl;
}
void storePlaintext(char key[])
{
char plaintextArray[8];
cout << "Please enter 8bit plaintext" << endl << "==> ";
cin >> plaintextArray;
cout << plaintextArray << endl << key[1] << endl;
//cout << plaintextArray << endl << key << endl;
}
I should get a print out of: 00000000 and 1111111111 on the next line followed by 1111111111 But I get 0000000 then "c" (or something random) followed by 111111111. WHY is this happening? I should be able to pass a array like i'm doing with no problem right? I need to be able to pass arrays from function to function and use the data inside them. ANY help will be much appreciated. Thanks
Upvotes: 0
Views: 68
Reputation: 35455
Use std::string
.
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
void storePlaintext(const string& key);
void storeKey()
{
std::string keyArray;
cout << "Please enter 10bit key" << endl << "==> ";
getline(cin, keyArray);
storePlaintext(keyArray);
cout << keyArray << endl;
}
void storePlaintext(const string& key)
{
string plaintextArray;
cout << "Please enter 8bit plaintext" << endl << "==> ";
getline(cin, plaintextArray);
if ( key.size() > 1 )
cout << plaintextArray << endl << key[1] << endl;
}
Note the use of std::string
, std::getline
, and passing parameters by (const) reference. Also, the check to ensure that the key
has more than 1 character is done, since accessing key[1]
with a string of length 1 or less is undefined behavior.
Upvotes: 2