gpt4 book ai didi

c++ - 矩阵类输入运算符重载 >> 在 C++ 中

转载 作者:太空宇宙 更新时间:2023-11-04 13:23:54 24 4
gpt4 key购买 nike

我创建了一个矩阵类,其中包含点对象的 vector vector (我创建的另一个类)。矩阵中的每个点都是可走的或不可走的(矩阵实际上是一个迷宫)。 1 适合步行,0 不适合。我想以这种形式获得矩阵:4 4//迷宫的大小(矩阵)1 0 1 0(输入)1 1 0 0(输入)0 1 1 0(输入)1 0 1 1(输入)

我试图逐行获取,然后通过流字符串分隔点(1 和 0)。这是我的代码:

    istream & operator >> (istream& input, maze inMaze) {

string rowStream;
string tmpWord;
int num, colCounter; //num = 1 or 0, colCounter = col index

for (int rowIndex = 0; rowIndex < inMaze.rowsSize; rowIndex++){ //over the rows
int colIndex = 0;
bool isWalkable;
input >> rowStream; //input to string
stringstream seperateWord(rowStream); //string to stream string

while (seperateWord >> tmpWord) { //sstring seperate space bars in string, reprasant a row

if (tmpWord == "0") isWalkable = false; //in maze matrix, zero means not a path
else if (tmpWord == "1") isWalkable = true; //else 1 = a path
else throw "invalid input"; //wrong input (num in matrix not 0 nor 1)
inMaze.getMaze[rowIndex][colIndex].setPoint(rowIndex, colIndex, isWalkable); //set point in maze
colIndex++; //next col
} //done filling a row, to next row
}

没用。它总是在第一行之后结束获取输入,并用 1 填充所有内容。我做错了什么?

感谢您的帮助!抱歉我的英语不好.. :-)

最佳答案

input >> rowStream;行的问题用getline(input,line);替换,linestring 类型。

>>> 文件的运算符接受一个以空格结尾的参数!

比如:00 1 0 11,第一个参数是00,第二个是1...

在你的情况下使用 stringstream 这意味着你必须使用整个 line

如:0 1 0 1 0 1,使用 getline 获取它,然后使用 stringstream 获取正确的输入。 0 然后 1 ...

关于c++ - 矩阵类输入运算符重载 >> 在 C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33999715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com