简体   繁体   中英

How to scan a txt file and input into matrix c++

I have to scan a file like "6 6 2 3 5 5 1" that represents (r, c, x, y, a, b, o) where r and c is dimensions of matrix, (x,y) is position of player, (a,b) is position of goal, and o is number of obstacles. How do I go about scanning this information from a txt file? I'm new to c++ and I know how to do this in java so I'm trying to basically convert it into c++

This is what I have so far:

Board(int r, int c, int x, int y, int a, int b, int o) {
rows = r;
cols = c;
player_x = x;
player_y = y;
goal_x = a;
goal_y = b;
obstacles = o;
}

read_board (board *b, r, c, x, y, a, b, o){
scanf("%d %d", &(b->rows),  &(b->cols), &(b->player_x), &(b->player_y), &(b->goal_x), &(b->goal_y), &(b->obstacles)
}

You've completely omitted the parameter types and the return value of the function. You'll need references for that. You also forgot a few %d specifiers in the scanf format argument.

void read_board(board *b, int &r, int &c, int &x, int &y, int &a, int &b, int &o)
{
    scanf("%d %d %d %d %d %d %d", &b->rows, &b->cols, &b->player_x, &b->player_y, &b->goal_x, &b->goal_y, &b->obstacles);
}

Ok, this is still pretty much rubbish that leads nowhere, where's the file BTW?
Since you're using c++ , read_board should be also a member function of Board and take no parameters, only operate on member variables.
Since you're using c++ , leave printf , scanf and other obsolete functions for c++ behind and use streams:

bool Board::read_board()
{
    std::ifstream ifs("file.txt");
    return ifs >> rows >> cols >> player_x >> player_y >> goal_x >> goal_y >> obstacles;
}

The function will return whether the file's been successfully read. I hope you'll figure something out of this. If you don't know what file to include in order to use std::ifstream , google it. If you don't know what the operator>> or operator bool does for std::ifstream and why is it in if condition, google it. Also, use the initializer list instead of an assignment in the constructor.

Since you mentioned scanf , here's a (pretty ugly) C alternative:

FILE *fp = NULL;
if ((fp = fopen("your file name", "r")) != NULL) {
    fscanf(fp, "%d %d %d %d %d %d %d", &(b->rows),  &(b->cols), &(b->player_x), &(b->player_y), &(b->goal_x), &(b->goal_y), &(b->obstacles));
    fclose(fp);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM