c++程序不从文件中读取字符
C++ Program Not Reading Characters from File
所以,我试图让程序读取一个文件并打印出晴天,阴天和雨天的数量。它一直输出0。我错过了什么?我试图将文件从。dat更改为。txt,但仍然是相同的结果。以下是数据文件中的内容:
RRCSSSCSCRRRCSSSCSSRSCCRCRRCSSSSSCCSSSCCSSSCCSSSCRCRCCSSSSSSSSSSCSSSCSSSCRRCCCSSSSSCSSSSCS
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
const int MONTH = 3;
const int DAY = 30;
char name[MONTH][DAY] = {"June", "July", "August"};
char rain = 'R';
char sun = 'S';
char cloud = 'C';
char letter;
int day = 0;
int count = 0;
int rainy = 0;
int cloudy = 0;
int sunny = 0;
ifstream inputFile;
cout << " Weather for Summer Monthsn";
cout << "--------------------nn";
inputFile.open("C:rainorshine.dat");
if (inputFile)
{
cout << "Error opening data file.n";
system("pause");
}
else
{ cout << "Weather Reportnn";
while (inputFile >> letter)
{
cout << letter << endl; // print out characters read from file
}
for (count = 0; count < MONTH; count++)
{
for (day = 0; day < DAY; day++)
{
cout << name[count][day];
inputFile >> name[count][day];
if (name[count][day] == 'R')
rainy++;
else if (name[count][day] == 'S')
sunny++;
else if (name[count][day] == 'C')
cloudy++;
}
cout << endl;
cout << " Sunny Days Total: " << rainy << endl;
cout << " Rainy Days Total: " << sunny << endl;
cout << " Cloudy Days Total: " << cloudy << endl << endl;
}
system("pause");
return 0;
inputFile.close();
}
}
This:
while (inputFile >> letter)
{
cout << letter << endl; // print out characters read from file
}
咀嚼所有的字母,当它完成时,您在文件的末尾。因此,当您尝试在for
循环中再次读取数据时,没有任何内容可读。
"C:rainorshine.dat"
// ^^
这不是一个后跟'r'
的反斜杠,它是一个转义序列,用于换行字符。您需要使用正斜杠或转义反斜杠本身:
"C:/rainorshine.dat"
或"C:\rainorshine.dat"
这意味着你永远不会打开文件。如果你的病情
if (!inputFile) // notice the !
{
cout << "Error opening data file.n";
代替逻辑错误
if (inputFile) ...
行后;
while (inputFile >> letter)
{
cout << letter << endl; // print out characters read from file
}
您需要重新打开文件或从开始处查找。当你下次尝试读取文件时,你已经在文件的末尾了,所以你什么也得不到。
之类的;
inputFile.seekg(0, inputFile.beg);
相关文章:
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 从矢量C++读取字符时出现问题
- 从格式化输入操作中获取读取字符数
- 使用 cin.get 读取字符数组
- 按下回车键时,如何使数组停止读取字符
- C++:读取字符是不正确的
- 如何从输入文件中读取字符并将其存储到向量中?
- 线程函数无法从堆上分配的缓冲区中读取字符
- 使用 cin.get() 读取字符
- C++:使用 fgets() 读取字符输入时出错
- C++ 从文件中读取字符,计算每个字符并进行排序
- C ++ ifstream 无法读取字符串,并且在读取字符时出错
- 逐字读取字符数组,无需字符串函数
- 是否有任何方法可以在用户输入文本时读取字符
- 从字符串中读取字符时出错
- 如何按字符从文件到2D数组读取字符
- 重载>>运算符和读取字符
- 从堆栈中读取字符后,如何修复不正确的文件输出
- 如何从文件中读取“”字符
- 读取字符 * 始终具有相同的地址