我正在尝试将 char[] 传递给另一个函数,但出于某种原因,我不断收到奇怪的输出,但没有错误。我有以下方法:
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;
}
我应该在下一行打印出:00000000 和 1111111111,然后是 1111111111 但我得到 0000000,然后是“c”(或随机数),然后是 111111111。为什么会这样?我应该能够像我一样毫无问题地传递数组,对吧?我需要能够将数组从函数传递到函数并使用其中的数据。任何帮助都感激不尽。谢谢
最佳答案
使用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;
}
注意 std::string
、std::getline
的使用,以及通过 (const) 引用传递参数。此外,检查以确保 key
具有超过 1 个字符,因为使用长度为 1 或更短的字符串访问 key[1]
是未定义的行为。
关于c++ - 将 char[] 传递给另一个函数时出现奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25955776/