我想我没有完全理解指针,但是为什么这里的输出有所不同?

I think I am not understanding pointers fully, but why is there a difference in the outputs here?

本文关键字:为什么 这里 有所不同 输出 指针      更新时间:2023-10-16

下面我有一段代码。基本上,我想知道为什么当我单独打印contextFile[0]contextFile[1]与通过for循环时输出会有所不同。

contextfile.txt(在这种情况下是target_file_name的值)中,我有以下内容:

山核桃迪科里点有一个小农场,你感觉到我。

这是代码:

cin >> target_file_name;
ifstream fileExist(target_file_name);
if (fileExist)
{
int count = 0;
int contextSize = 1000;
int keySize = 1000;
char *contextFile;
char *keyFile;
contextFile = new char[contextSize];
keyFile = new char[keySize];
string command;
fileExist >> contextFile[count];
while (!fileExist.fail())
{
count++;
fileExist >> contextFile[count];
}
cout << "printing individual: " << contextFile[0] << contextFile[1];
cout << "Printing the contextfile array: " << endl;
for (int i = 0; i < count; i++)
{
cout << contextFile[count];
}

当我单独打印时,我得到hi,这是正确的输出。

当我通过for循环打印时,我只是直接================.

为什么会有区别?

因为你打印

cout << contextFile[count];

一遍又一遍,而不是

cout << contextFile[i];

在您的循环中,导致未定义的行为,因为contextFile[count]从未初始化过。

这是因为您在for循环中只打印一个值。

for (int i = 0; i < count; i++) {
cout << contextFile[count];
}

您需要对此进行更改

for (int i = 0; i < count; i++) {
cout << contextFile[i];
}

您的输入文件中有 50 个字符。 因此,在读取循环完成后,count为 50,并且contextFile[0](包括contextFile[49])已填充数据。

然后你输出contextFile[]的前两个单独的字符,这很好。

然后你正在循环遍历contextFile[]的前count个字符,这也很好。 但是在每次循环迭代中,您都会输出contextFile[50],它没有填充任何有效数据。 您应该输出contextFile[i]

for (int i = 0; i < count; i++)
{
//cout << contextFile[count];
std::cout << contextFile[i];
}

话虽如此,我建议根本不使用char[]

std::getline(std::cin, target_file_name);
std::ifstream theFile(target_file_name);
if (theFile)
{
std::vector<char> contextFile;
char ch;
theFile.seekg(0, std::ios_base::end); 
size_t size = theFile.tellg();
theFile.seekg(0, std::ios_base::beg); 
contextFile.reserve(size);
while (theFile >> ch)
{
contextFile.push_back(ch);
}
/* alternatively:
contextFile.reserve(size);
std::copy(
std::istream_iterator<char>(theFile),
std::istream_iterator<char>(),
std::back_inserter(contextFile)
);
*/
/* alternatively:
contextFile.resize(size);
theFile.read(&contextFile[0], size);
size = theFile.gcount();
contextFile.resize(size);
*/
std::cout << "printing individual: " << contextFile[0] << contextFile[1]" << std::endl;
std::cout << "Printing the contextfile array: " << std::endl;
for (int i = 0; i < contextFile.size(); i++)
{
std::cout << contextFile[i];
}
/* alternatively:
for (std::vector<char>::iterator iter = contextFile.begin(); iter != contextFile.end(); ++iter)
{
std::cout << *iter;
}
*/
/* alternatively:
std::copy(
contextFile.begin(),
contextFile.end(),
std::ostream_iterator<char>(std::cout)
);
*/
/* alternatively:
std::cout.write(&contextFile[0], contextFile.size());
*/