【发布时间】: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++