【问题标题】:Appending a text file to a char array, receiving garbage output将文本文件附加到 char 数组,接收垃圾输出
【发布时间】:2017-11-01 21:00:31
【问题描述】:

当我将文件添加到 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
}

我相信它的打印垃圾,因为它认为数组消息中没有任何内容,但我不知道为什么“什么都没有”。

【问题讨论】:

  • 您不会在两组读取之间重置文件,因此您不会将任何内容放入message。您正在打印分配时剩余的垃圾。
  • @Ron 将文件内容添加到 char 数组中。因此,如果文件包含“hello world”,它将进入一个数组,如 {'h', 'e', 'l', 'l', 'o',。 . . }
  • @MarkRansom 啊...我不知道这是必需的。谢谢!
  • 您正在将所有文件读入字符串为什么不将字符串转换为数组而不是再次读取?

标签: c++ arrays file loops


【解决方案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,因此数组只是被声明而没有被初始化,因此你知道它包含垃圾值。

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

【讨论】:

    猜你喜欢
    • 2011-06-26
    • 2018-09-12
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    相关资源
    最近更新 更多