#c #readfile #minesweeper
#c #readfile #тральщик
Вопрос:
Я делаю программу, которая считывает файлы пользовательского ввода (координаты) и создает мини-игру minesweeper с бомбами, размещенными в заданных координатах. Моя проблема с опцией чтения, ввод должен быть: read filename . Я пытаюсь разделить строку на две части, но у меня не очень получается.
ps. Я новичок, поэтому, вероятно, допустил глупые ошибки, и код сейчас в беспорядке, потому что он еще не закончен.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define map_SIZE 25
void mapa(void);
void printUsermap(void);
void readf(void);
void bombmaker (void);
int x, y, i, j;
int numbers;
char mines;
char map[map_SIZE][map_SIZE];
char final_map[map_SIZE][map_SIZE];
char umap[map_SIZE][map_SIZE];
void mapa(void){
int column, row;
for(column = 0; column < map_SIZE; column )
for(row = 0; row < map_SIZE; row )
umap[column][row] = '_';
}
void printUsermap(){
int column, row;
system("cls");
for(column = 0; column < map_SIZE ; column )
{
for(row = 0; row < map_SIZE; row )
{
printf("%c", umap[column][row]);
}
printf("n");
}
}
void bombmaker (){
int i=0, j=0;
if( map[i][j] != '*')
{
map[i][j] = '*';
final_map[i][j] = map[i][j];
mines ;
}
}
void readf(){
char string[50] = "practice try.ini ";
// Extract the first token
char * token = strtok(string, " ");
// loop through the string to extract all other tokens
while( token != NULL ) {
printf( " %sn", token ); //printing each token
token = strtok(NULL, " ");
}
//reading second string
/*char buff[128];
int i = 0;
scanf("%s",buff);
char *p = strtok (buff, " ");
char *div_var[2];
while (p)
{
div_var[i ] = p;
p = strtok (NULL, " ");
}
for (i = 0; i < 2; i )
{
printf("data[%i] = %sn", i 1, div_var[i]);
}
char ch, file_name[25];
printf("> ");
gets(file_name);
FILE *fp;
fp = fopen(div_var[1], "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are:n", file_name);
while((ch = fgetc(fp)) != EOF)
printf("%c", ch); */
}
int main()
{
char option[128];
// MENU
printf(" -----------------------------------------------------n");
printf(" read <filename> - read input filen show - show the mine mapn trigger <x> <y> - trigger mine at <x> <y>n plant <x> <y> - place armed mine at <x> <y>n export <filename> - save file with current mapn quit - exit programn sos - show menun ");
printf(" -----------------------------------------------------n");
do{
printf(">");
scanf ("%s", option);
//Opcao read
//if (strcmp(option, "plant")!=0 || strcmp(option,"tigger")!=0 || strcmp(option, "show")!=0 || strcmp(option, "export")!=0 || strcmp(option, "quit")!=0){
if (strcmp(option, "read")==0){
readf();
}
// Option show
if (strcmp(option, "show")==0)
{
mapa();
printUsermap();
}
// Option trigger
else if (strcmp(option, "trigger")==0)
{
scanf("%d %d", amp;x, amp;y);
if (x >= 25 || y >= 25){
fprintf(stdout, "Invalid coordinaten");
}
else if (map[i][j] == '.'){
map[i][j] = '*';
final_map[i][j] = map[i][j];
mines ;
}
else{
fprintf(stdout, "No mine at specified coordinaten");
//fprintf(stdout,"Hello. My name is Inigo Montoya. You killed my father. Prepare to dien");
}
}
// Option plant
else if (strcmp(option, "plant")==0)
{
scanf("%d %d", amp;x, amp;y);
if (x >= 25 || y >= 25){
fprintf(stdout, "Invalid coordinaten");
}
else if (map[i][j] == '_'){
map[i][j] = '.';
final_map[i][j] = map[i][j];
mines ;
}
else if (map[i][j] == '*'){
map[i][j] = '.';
final_map[i][j] = map[i][j];
mines ;
}
else{
//printf ("You're gonna need a bigger boatn");
}
}
// Opcao export
else if (strcmp(option, "export")==0)
{
FILE * fp;
fp = fopen("file1.text","w");
fprintf(fp, "teste");
fclose(fp);
}
// Opcao SOS
else if (strcmp(option, "sos")==0)
{
printf(" -----------------------------------------------------n");
printf(" read <filename> - read input filen show - show the mine mapn trigger <x> <y> - trigger mine at <x> <y>n plant <x> <y> - place armed mine at <x> <y>n export <filename> - save file with current mapn quit - exit programn sos - show menun ");
printf(" -----------------------------------------------------n");
}
}
while (strcmp(option,"quit")!=0);
return 0;
}
Комментарии:
1.
char buff[128];
это не содержит ничего действительного, что вы здесь анализируете? и неясно, в чем заключается ваш вопрос, вам следует четко задать конкретный вопрос2. Пожалуйста, отформатируйте свой код.
Ответ №1:
Прекратите использование scanf
. Прочитайте ввод с fgets
помощью . Затем используйте strtok
(или лучше strtok_r
) для первого разделения действия. Если действие «прочитано», вы можете разделить имя readf
файла.
в main
:
char line[256];
fgets(line, sizeof(line), stdin);
char *action = strtok(line, " tn");
затем readf
вы можете получить параметр filename с помощью
char *filename = strtok(NULL, " tn");
Обработка ошибок была исключена для краткости.