c++程序不从文件中读取字符

C++ Program Not Reading Characters from File

本文关键字:读取 字符 文件 程序 c++      更新时间:2023-10-16

所以,我试图让程序读取一个文件并打印出晴天,阴天和雨天的数量。它一直输出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);