【问题标题】:Trying to read a file into a char array试图将文件读入 char 数组
【发布时间】:2013-04-24 18:33:04
【问题描述】:

我正在尝试将文件中的所有字符读入数组。假设声明了所有变量,为什么所有字符都没有被读入我的数组。当我输出“storeCharacters[]”数组中的一些字符时,会返回垃圾。请帮忙。

这是我的功能:

void countChars(ifstream& input, char storeCharacters[])
{
int i = 0;
    while( !input.eof() )
    {
        input.get(storeCharacters[i]);
        i++;
    }
}

【问题讨论】:

  • 如何为字符分配空间?
  • 您可以使用input.read方法消除该功能。
  • 尝试使用 while(input.good() && !input.eof() ) 因为 eof 不仅是表示流不可读的属性。但是,“假设所有变量都被声明......”:-)

标签: c++ arrays char


【解决方案1】:

在 while 循环之后尝试将 storeCharacters[i] = '\0' 添加到 null 终止字符串。

【讨论】:

  • 我不确定这是否有任何作用...我不知道如何为字符分配空间。
【解决方案2】:

如果您知道文件的最大大小,则可以轻松解决您的问题,然后只需将数组设置为该大小并使用\0 对其进行初始化。

假设您文件中的最大字符数为10000

#define DEFAULT_SIZE 10000
char  storeCharacters[DEFAULT_SIZE];
memset (storeCharacters,'\0',DEFAULT_SIZE) ;

下面的帖子应该是使用缓冲区读取文件的正确方法,它具有内存分配以及您需要知道的所有内容:

Correct way to read a text file into a buffer in C?

【讨论】:

    【解决方案3】:
    #include <iostream>
    #include <fstream>
    #include <iomanip>
    #include <string>
    #include <cstdlib>
    
    
    using namespace std;
    
    
    void getFileName(ifstream& input, ofstream& output)  //gets filename
    {
    string fileName;
    
    cout << "Enter the file name: ";
    cin >> fileName;
    input.open(fileName.c_str());   
    if( !input )
        {
            cout << "Incorrect File Path" << endl;
            exit (0);
        }
    output.open("c:\\users\\jacob\\desktop\\thomannProj3Results.txt");
    }
    
    void countWords(ifstream& input)  //counts words
    {
    bool notTrue = false;
    string words;
    int i = 0;
    
    while( notTrue == false )
    {
        if( input >> words )
        {
            i++;
        }
        else if( !(input >> words) )
            notTrue = true;
    }
    cout << "There are " << i << " words in the file." << endl;
    }
    
    void countChars(ifstream& input, char storeCharacters[], ofstream& output)  // counts characters
    {
    int i = 0;
    
            while( input.good() && !input.eof() )
            {
                    input.get(storeCharacters[i]);
                    i++;
            }
            output << storeCharacters[0];
    }
    
    void sortChars()  //sorts characters
    {
    }
    
    void printCount()  //prints characters
    {
    }
    
    int main()
    {
    
    ifstream input;
    ofstream output;
    
    char storeCharacters[1000] = {0};
    
    getFileName(input, output);
    countWords(input);
    countChars(input, storeCharacters, output);
    
    return 0;
    }
    

    【讨论】:

    • 我确定它很简单......为什么我不能将文件中的字符存储到 countChars 函数下的 storeCharacters[] 数组中?
    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 2015-07-11
    • 2012-10-20
    相关资源
    最近更新 更多