在C++中一次一行地从文本文件中读取int(好的字符,然后转换)时出现问题

Trouble reading ints (well chars and then converting) from text file one line at a time in C++

本文关键字:字符 然后 问题 int 转换 文本 一次 C++ 一行 文件 读取      更新时间:2023-10-16

我在这里以及cplusplus.com和各种来源阅读了不同的帖子/问题,但在阅读文本文件时,我的代码仍然存在问题。文本文件每行有一个int(个位数)。例如:5.1.2.5.。。。等每个数字都应该代表一个特定的变量。我遇到麻烦了,我想是因为"\n"字符?因为它将读取第一个int,但随后第二个int和其他几个int将为-38!!我试过ignore()的方法(尽管可能我做错了?),但没有成功。我确信这是一个快速的解决方案,可能会盯着我的脸,但我看不见!以下是我的代码中有问题的部分:

void RegOffice::analyzeFile()
{
    cout << "Please enter the location of the file to be read. " << endl;
    cin >> fileName;
    cout << endl;
    inData.open(fileName.c_str());
    if (inData.is_open())
    //while file is open
    {
        while(inData)       //While file is still good
        {
            char c;
            /* 
            The function below reads in one int at a time on each line. First line is the number of windows
            open. The next line will be the time (or clock tick) at which the next student(s) arrive. 
            The next line will be the number of students that arrive at that time. The lines after that
            will be the amount of time each student needs at a window in minutes.
            */
            c = inData.get();               //Gets the number of windows open
            winOpen = c - '0';  
            cout << "Windows Open: " << winOpen << endl;            
            windows = new GenQueue<Window>(winOpen);    //Sets up an array of open windows
            c = inData.get();
            time = c - '0';     //Gets the first time that students arrive
            cout << "Time: " << time << endl;   
            c = inData.get();
            numStudents = int(c - '0');     //Gets the number of students that enter the line at that time
            cout << "Number of Students: " << numStudents + 1 << endl;  
            for(int i = 0; i < numStudents; i++)    // numStudents is the number read in by the text file
            {
                Student *stu = new Student(); //creating a new instance of a student
                c = inData.get();
                stu->setTimeAtWin(c - '0');  //Setting student's wait time to the next number in file
                stu->setArrivalTime(time);   //Setting student's arrival time
                cout << "New Student created! Info for Student #" << i << ":" << endl;
                stu->print();
                line->addBack(*stu);   
            //Inserting that student to the back of the queue (The first student                                                       
            //will be first in line though if no one is in line)
            }
        }
     }
  }

你在读ifstream吗?

#include <fstream>
std::ifstream infile("inData.txt");

然后读一行,做

int c;
infile >> c;

我现在看到问题了。从这个引用中,函数istream::get()有这样的原型:int get();我想你可以看到它在你的程序中可能不起作用。

相关文章: