When I try and compile this I get the error shown above, and I don;t know how to fix this. I'm VERY new to C++ so please feel free to destroy everything, as I will learn from advice.
Input:
.............
.............
..XXX.....X..
..XXX.....X..
..XXX........
..XXX........
..XXXXXXX....
..XXXXXXX....
..XXXXXXX....
.............
.............
Output:
.............
.............
..OOO.....O..
..OOO.....O..
..OOO........
..OOO........
..OOOOOOO....
..OOOOOOO....
..OOOOOOO....
.............
.............
If i change it so that instead of
if (board[i][j] == older) {
board[i][j] = newer;
I do.
if (board[i][j] == "X") {
board[i][j] = "0";
It works
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <vector>
int main(int argc, char* argv[]) {
std::ifstream in_str(argv[1]);
//Check that the file was properly opened
if (!in_str.good()) {
std::cout << "Can't open " << argv[1] << " to read.\n";
return (1);
}
std::string value;
std::vector<std::string> board;
while (in_str >> value) {
board.push_back(value);
}
if (argv[3] == std::string ("replace")) {
std::string older(argv[4]);
std::string newer(argv[5]);
for (unsigned int i = 0; i < board.size(); i++) {
for (unsigned int j = 0; j < board[0].size(); j++) {
if (board[i][j] == older) {
board[i][j] = newer;
}
}
}
Since board
is defined as:
std::vector<std::string> board;
board[i][j]
evaluates to a char&
.
Since older
and newer
are defined to as:
std::string older(argv[4]);
std::string newer(argv[5]);
The following are wrong:
board[i][j] == older
board[i][j] = newer;
You can't compare a std::string
with a char
and you can't assign a std::string
to a char
.
The following are also wrong:
board[i][j] == "X"
board[i][j] = "O";
You can't compare a char const*/char*/char [2]
with a char
and you can't assign such an object to a char
.
You can use:
board[i][j] == older
board[i][j] = newer;
if older
and newer
are of type char
. I suggest changing the declaration of those variables to:
char older = argv[4][0];
char newer = argv[5][0];
any item in board matrix is char. and older and newer are string (char*) in if (board[i][j] == older) code you try to compare char * and char set older and newer to char instead of string
To fix this problem, You might compare with older[0]
and newer[0]
since they will return refrence to char which should work.
As others have pointed out, as of now your comparing a string object with a single char which is problematic. But older[0]/newer[0] will return reference to char.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.