在C++中一次一行地从文本文件中读取int(好的字符,然后转换)时出现问题
Trouble reading ints (well chars and then converting) from text file one line at a time in C++
我在这里以及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();
我想你可以看到它在你的程序中可能不起作用。
相关文章:
- 如何在字符串中找到字符,然后在C++中提取其余的字符串
- 首先按给定顺序打印所有数字,然后使用 Array 打印所有字符和其他符号
- 生成随机.txt文件,10行,10列。充满随机:"*"、"#"、"@"。然后将随机字符替换为'P'
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 有没有办法搜索向量的元素,<String>然后检查它是否包含特定的字符,如果它确实打印了它
- 从文件中找出字符'a',然后计算字符出现的行数
- 按字母顺序排序字符数组,然后按长度排序
- 当找到来自 RHS 的字符"\"时,从主字符串中获取单词或子字符串,然后擦除其余部分
- 将无符号字符转换为字符串,然后再次转换为无符号字符
- 将整数转换为字符数组,然后将其转换回来
- 打开一个文件,修改每个字符,然后执行反向操作不输出原始文件
- C :在字符串中找到一个char,然后在先前的char之后找到另一个字符
- 文字符号和字符串变量之间的串联然后返回常量字符*
- 获取字符数组地址,然后转换为指针字符
- 如何从字符串中读取字符,然后将其关联到数值
- 选择字符数组中的单词,然后一一比较它
- C++ - 从 cin 中读一个替身,然后是一个字符
- 字符指针指向字符串,然后指向字符串数组。"./a.out"中的错误:malloc():内存损坏:0x0900c3b0***
- 在C++中一次一行地从文本文件中读取int(好的字符,然后转换)时出现问题
- 如何将多个整数添加到字符数组中,然后将它们拉出