将文本文件附加到char数组,接收垃圾输出

时间:2017-11-01 21:00:32

标签: c++ arrays file loops

当我将文件添加到char数组,然后打印时,我得到垃圾输出(随机ASCII符号)。该文件仅包含文本(段落)。

代码如下:

int arraySize = 0;
string line;
while(getline(inFile, line)){
    //cout << line << endl; // this will print array fine.
    arraySize += line.length();
}
char message[arraySize];
char encrypted[arraySize];
//adds file to array
int i = 0;
while(inFile.good() && !inFile.eof()){
    inFile.get(message[i]);
    i++;
}
message[i] = '\0';
//prints array
for(int i = 0; i < arraySize; i++){
    cout << message[i]; //this returns garbage values
}

我相信它的印刷垃圾是因为它认为阵列消息中没有任何内容,但我不知道为什么那里没有#34;

1 个答案:

答案 0 :(得分:1)

原因是当你计算文本的长度时你到达了文件的末尾,因此读指针位于文件的末尾,你再次使用它来读取文本文件。

要做到这一点:再次将读取指针添加到开头:

inFile.clear();
inFile.seekg(0, ios::beg);
while(inFile.get(message[i])){
    i++;
}

也不要使用:while (!infile.eof())它被认为是不正确的。

  • 我建议使用std::vector您不介意文件大小或内存的任何分配/取消分配。所以你的代码可以是这样的:

    std::ifstream inFile("data.txt"); // your file name here
    std::string strLine;
    std::vector<std::string> vecStr;
    
    while(std::getline(inFile, strLine))
        vecStr.push_back(strLine);
    
    for(int i(0); i < vecStr.size(); i++)
        std::cout << vecStr[i] << std::endl;
    
    inFile.close();
    

您是否看过上面代码的魅力?

  • 注意:您获得了垃圾值,因为该数组仅被声明但未初始化:

第一次读取获取文本的长度。但是将读指针移到了最后,然后你做了:

while(inFile.good() && !inFile.eof()){ // Will fail because inFile.eof() is true from the previous read.
    //std::cout << "Inside the reading loop" << std::endl;
    inFile.get(message[i]);
    i++;
}

正如您在上面所看到的,循环将不会被执行,因为前一个读取到达了eof,因此数组刚刚被声明而没有被初始化,因此您知道它包含垃圾值。

要确认循环未执行,请取消注释上面的行并查看循环是否已执行。结果是没有打印消息,这意味着它没有被执行。