【问题标题】:Turbo C++ compiler not reading text file properly. (Only when I make it a .dat file, is it read properly)Turbo C++ 编译器无法正确读取文本文件。 (仅当我将其设为 .dat 文件时,它才能正确读取)
【发布时间】:2017-07-17 14:07:52
【问题描述】:

我在使用 C++ 和 C 时遇到问题,我的 ifstream 对象或文件指针无法正确读取文本文件,并在输出时显示非法字符。但是,当我读取 .dat 文件时,它会输出正确的结果。

这是 C 代码:

#include <stdio.h>
#include <conio.h>
#include <ctype.h>
void main() {
    FILE *file;
    char ch;
    file = fopen("code.dat", "r");
    while((ch = getc(file)) != EOF)
        printf("%c", ch);
    getch();
    fclose(file);
}

这是 CPP 代码:

#include <fstream.h>
#include <iostream.h>
#include <conio.h>
#include <string.h>

int main() {
    clrscr();
    fstream file;
    file.open("code.dat", ios::in);
    char ch, c;
    char token[6];
    int id = 0, op = 0, key = 0;
    while (!file.eof()) {
        file >> ch;
        if(ch == ' ') {
            if ((ch > 64 && ch < 91) || (ch > 96 && ch < 123))
                id += 1;
        }
    }

    cout << id;
    file.close();
    getch();
    return 0;
}

【问题讨论】:

  • Turbo C++ 是一个古老的编译器,已停止支持。它使用语言标准化之前的 C++ 方言。如果你想学习 C++,就像它现在使用的方式一样,升级到现代的东西。 GCC 和 Clang 是不错的选择。
  • “我遇到了 C++ 和 C 的问题,我的 ifstream 对象在哪里” - 你没有。 C 没有“ifstream 对象”。这是一种完全不同的语言!
  • @Olaf C 的文件指针,以及 C++ 的 ifstream 对象.. 我知道很多兄弟..
  • @AkhileshIyer:好吧,你至少似乎不知道How to Ask。 (哦,还有:如果您不要使用街头俚语……“兄弟”,我将不胜感激。

标签: c++ fstream file-management turbo-c++


【解决方案1】:

由于您遇到文本文件问题,请尝试以二进制模式打开它,即:添加 ios::binary。于是代码变成了:

file.open("code.txt",ios::in|ios::binary);

当您想阅读整个单词时,也可以使用 file>>ch。既然您想逐个字符地阅读,请尝试

file.get(ch);

【讨论】:

    【解决方案2】:

    代码中可能存在潜在问题:

    if(ch == ' ')
    {
        if((ch > 64 && ch < 91) || (ch > 96 && ch < 123))
            id += 1;
    }
    

    外部if语句排除了内部if语句执行的可能性(空格的ASCII码是32,所以ch不能同时是32并且满足两个条件之一,所以@987654326 @ 永远不会增加)。

    这似乎不会产生您所描述的行为,它应该只会导致将0 打印到stdout

    如果没有输出示例,很难知道出了什么问题 - 我们需要MCVe 来提供好的建议。在这里,您的 C 代码只打印文件的内容,而 C++ 代码计算字母字符的数量(也许,我只是略过它)。那么哪一个失败了?如何?给我们一个输出示例,并说明您期望每个人做什么。

    正如其他人所提到的,Turbo C++ 已经过时 - 你应该开始使用 g++ 或 clang。

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 1970-01-01
      • 2023-01-14
      • 2021-05-24
      • 2015-01-22
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多