【问题标题】:How do I read character by character from a text file and put it in a character array?如何从文本文件中逐个字符读取并将其放入字符数组中?
【发布时间】:2012-11-25 03:15:56
【问题描述】:

我正在尝试从文本文件中逐个字符读取直到 EOF,将它们放入字符数组中,以便之后可以对其进行操作。用 g++ 编译没有错误,运行时,我被提示输入输入文件,但它只是挂起。

int main (int argc, char *argv[]) {
    string filename;
    ifstream infile;

    char *cp, c[1024];
    memset (c, 0, sizeof(c));
    cp = c;

    cout << "Enter file name: " << endl;
    cin >> filename;

    //open file
    infile.open( filename.c_str() );

    //if file can't open
    if(!infile) {
        cerr << "Error: file could not be opened" << endl;
        exit(1);
    }

    while (!infile.eof()); {
        infile.get(c, sizeof(infile));
       // get character from file and store in array c[]
    }
}//end main

【问题讨论】:

  • 您不应该逐个字符地阅读。这已经不是 1980 年代了……
  • 我应该提到这是我的任务,但很高兴知道。

标签: c++


【解决方案1】:

您应该尝试istream::read() 方法而不是get()。这将有助于解决任何缓冲区溢出问题:

unsigned int chars_read = 0;
//...
// Read in the file.
if (!infile.read(c, sizeof(c))
{
    // Handle the read error here.
    // Also check for EOF here too.
}

// Obtain the number of characters actually read.
chars_read = infile.gcount();

【讨论】:

  • 谢谢,很有帮助!
【解决方案2】:

首先,您不想想测试eof()!不知怎的,我开​​始觉得堂吉诃德找到了我的风车。但是,我知道您需要检查输入是否成功在尝试读取它之后,因为在尝试读取流之前无法知道它是否会成功。

您的程序实际上没有挂起!它只是等待您输入sizeof(infile) 字符或结束输入(例如,在 UNIX 上使用 Ctrl-D,在 Windows 上使用 Ctrl-Z)。当然,这可能看起来像一个悬挂程序。您可以通过使用较小的尺寸来验证这确实是问题所在,例如4。当然,sizeof(infile) 几乎和一个小的随机数一样好:它是std::ifstream 类型的对象的大小,谁能知道那是什么?您可能打算使用sizeof(c) 来确保对get(c, n) 的调用不会写入超出c 的字符数。

【讨论】:

  • OP 还需要检查读取的字符数量与数组的容量。否则会发生缓冲区溢出。
  • 感谢大家,更改 sizeof(c) 并执行 infile.gcount() 有所帮助。我确实注意到,当我的文件被读取时,它只会读取到下一个返回行(因此只读取一行)?
  • 我曾使用过 infile.get() 和 infile.read(),但 infile.read() 会忽略新行。
【解决方案3】:

试试这个:

int cont = 0;
while(infile.good()) {
  c[cont++] = infile.get();
}

【讨论】:

  • 您的解决方案可能导致缓冲区溢出。如果文件大小大于 1024,则开始写入超出数组。
  • 是的,但不要怪我,他是限制的人:D
猜你喜欢
  • 2019-11-11
  • 1970-01-01
  • 2017-09-29
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多