我正在进行一个解决银行家算法的项目。我从一个文件中读取了输入,该文件定义了一个可用数组,一个分配资源和最大资源的矩阵。输入文件的结构为:
3 3 2
0 1 0
2 0 0
3 0 2
2 1 1
0 0 2
7 5 3
3 2 2
9 0 2
2 2 2
4 3 3
我要在矩阵中读取的代码是:
// get input for available resources
for (int r = 0; r < R; ++r) {
std::string numStr;
char in;
do {
input.get(in);
numStr += in;
} while (in != ' ');
avail_[r] = std::stoi(numStr);
}
// get input for allocated vector
for (int p = 0; p < P; ++p) {
for (int r = 0; r < R; ++r) {
std::string numStr;
char in;
do {
input.get(in);
numStr += in;
} while (in != ' ');
alloc_[p][r] = std::stoi(numStr);
}
}
// get input for max
for (int p = 0; p < P; ++p) {
for (int r = 0; r < R; ++r) {
std::string numStr;
char in;
do {
input.get(in);
numStr += in;
} while (in != ' ');
max_[p][r] = std::stoi(numStr);
}
}
我有一些循环,在读取矩阵后输出它们的值。输出为
Available:
3 3 2
Allocated:
1 0 0
0 0 2
1 1 0
2 5 3
2 2 0
它在读取分配矩阵后停止,甚至没有正确读取。我认为我使用std::ifstream.get((是错误的,但我不知道怎么回事。
我发现,如果我把所有数据放在一行中,它会正确地读取分配矩阵,但当我尝试读取最大矩阵时,我的程序仍然会暂停(尽管我在读取最大时使用了与分配矩阵相同的代码(。
请查看我用// CHANGE HERE
标记的评论
const int R = 3;
const int P = 5;
int avail_[3];
int alloc_[5][3];
int max_[5][3];
std::string line;
// get input for available resources
for (int r = 0; r < R; ++r) {
// std::string numStr;
// char in;
// do {
// input.get(in);
// numStr += in;
// } while (in != ' ');
// avail_[r] = std::stoi(numStr);
// CHANGE HERE: read int directly from input
if (!(input >> avail_[r])) {
std::cout << "Error readingn";
return 1;
}
}
// CHANGE HERE: read the blank line
//std::getline(input, line);
// get input for allocated vector
for (int p = 0; p < P; ++p) {
for (int r = 0; r < R; ++r) {
// std::string numStr;
// char in;
// do {
// input.get(in);
// numStr += in;
// } while (in != ' ');
// alloc_[p][r] = std::stoi(numStr);
// CHANGE HERE: read integer directly from input
if (!(input >> alloc_[p][r])) {
std::cout << "Error readingn";
return 1;
}
}
}
// CHANGE HERE: read the blank line
//std::getline(input, line);
// get input for max
for (int p = 0; p < P; ++p) {
for (int r = 0; r < R; ++r) {
// std::string numStr;
// char in;
// do {
// input.get(in);
// numStr += in;
// } while (in != ' ');
// max_[p][r] = std::stoi(numStr);
// CHANGE HERE: read integer directly from input
if (!(input >> max_[p][r])) {
std::cout << "Error readingn";
return 1;
}
}
}
std::cout << "Availablen";
for (int r = 0; r < R; r++)
{
std::cout << avail_[r] << " ";
}
std::cout << endl;
std::cout << "Allocatedn";
for (int p = 0; p < P; ++p) {
for (int r = 0; r < R; ++r) {
std::cout << alloc_[p][r] << " ";
}
std::cout << std::endl;
}
std::cout << "Maxn";
for (int p = 0; p < P; ++p) {
for (int r = 0; r < R; ++r) {
std::cout << max_[p][r] << " ";
}
std::cout << std::endl;
}