我为我的计算机科学类(class)编写了一个程序,用于验证和解决来自 .txt 文件的数独谜题,但我想更进一步,编写一个程序来简化输入和数独游戏。我相信你可以根据这段代码找出文件的格式。我唯一的问题是最后一个 cin 被跳过了,这个选项对我来说很重要。任何见解将不胜感激!!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct s {
s();
~s() {/*zzzz*/}
void show_grid();
void set (int &r, int &c, int &v) {g[r][c] = v;}
private:
int g[9][9];
};
//************************************************************************
void s::show_grid() {
//print game out to check it
cout << " | ------------------------------- |" << endl;
for (int k=0; k<81; k++) {
if (k%3 == 0)
cout << " |";
cout << " " << g[k/9][k%9];
if (k%9 == 8) {
cout << " |" << endl;
if ((k/9)%3 == 2)
cout << " | ------------------------------- |" << endl;
}
}
cout << endl;
}
//************************************************************************
s::s() {
//initialize all elements to zero
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
g[i][j] = 0;
}
}
}
//************************************************************************
void create_name (string &name) {
//append .txt extension LIKE IT OR NOT
string ext = name;
ext.erase(ext.begin(), ext.end() - 4);
if (ext.compare(".txt")!=0)
name.append(".txt");
}
//************************************************************************
int main () {
s g;
string name;
string yon("");
int count = 0;
int row, col, val, rcv;
ofstream os;
cout << "Enter game file name: ";
cin >> name;
create_name(name);
//open and do typical checks
os.open(name.c_str());
if (os.fail()) {
cerr << "Could not create " << name << ". Waaaah waaaaaaaaaah...\n\n";
return 0;
}
//useful output (hopefully)
cout << "Enter grid coordinates and value as a 3-digit number,\n"
<< "from left to right, row by row.\n"
<< "(e.g. 2 in first box would be 112)\n";
//take input as one int, to be user friendly
while (cin >> rcv && count < 81) {
row = (rcv / 100) - 1;
col = ((rcv / 10) % 10) - 1;
val = rcv % 10;
os << row << " " << col << " " << val << endl;
g.set (row, col, val);
count++;
}
os.close();
//From here down is broken, but it still compiles, runs, and works
cout << "Show grid input(y/n)?\n";
cin >> yon;
if (yon.compare("y")==0)
g.show_grid();
else if (yon.compare("n")==0)
cout << "Peace!\n";
return 0;
}
最佳答案
问题出在这里:
while (cin >> rcv && count < 81)
考虑当 count==81
时会发生什么: 首先,rcv
将从cin
输入,然后才出现条件 count < 81
将被评估为假。循环将停止,并且 rcv
的值将被忽略。如此有效,您阅读一个输入太多了。
你应该改变评估的顺序,这样count
首先检查:
while (count < 81 && cin >> rcv)
编辑:
根据您上面的评论,您实际上期望读取的值少于 81 个。在这种情况下,我建议让用户输入一个特殊值(例如 0)来终止循环。您只需要添加 if (rcv==0) break;
.如果你只是输入了一个无效的值,就像你显然在做的那样,cin
流将处于失败状态,进一步的输入将不会成功。
关于c++ - 数独输入程序跳过提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13181572/