C 如何输入以空格分隔的值(战舰游戏)

标签 c

所以,我必须在“c”中编写这个战舰游戏,其中我有一个函数,当调用该函数时,会要求输入棋盘的大小、2 行数字(现在它们做什么并不重要)以及代表战舰棋盘的棋盘。所以输入看起来像这样:

c

10 10

3 1 3 1 2 2 3 1 1 3

2 2 0 2 2 2 2 3 4 1

..........

..........

..........

..........

...~......

<.........

...~...^.~

..........

..........

..........

重要部分

我需要帮助,因为我无法将数字或字符单独存储在单独的变量中。我尝试使用 scanf() 但由于空格而不起作用。我怎么能这样做呢? (我正在寻找可能最简单的方法)

这符合我所拥有的:

void c(){
int a, c;
scanf("%d %d", &alt, &comp);
/*alt and comp are external. these will hold the first two numbers */

for(a=0; a< alt; a++){
    scanf("%d", &s[0][a]); 
}
for(c=0; c < comp; c++){
    scanf("%d", &s[1][c]);
} /* these two fors are supposed to get the first two rows of numbers to an external array */

for(a=0; a < alt, a++){
    for(c=0; c < comp; c++){
        scanf("%c", &tab[a][c]);
    }
}/* this is supposed to get the board to 'tab' (external) */
}

最佳答案

您可以尝试在 scanf 中添加一个空格,如下所示: scanf("%d ", &s[1][c]); 来消耗空格,但随后您需要特殊区分行中最后一个数字,因为它没有尾随空格。

相反,我会读取整行数字并使用 strtok在空格上分割线。

#include <string.h>
#include <stdio.h>

char[100] line;
char *number;
int i;

i = 0;
gets(line);
number = strtok (line, " ");
while(number != NULL;) {
    s[0][i] = atoi(number);
    number = strtok(NULL, " ");
    i += 1;
}

i = 0;
gets(line);
number = strtok (line, " ");
while(number != NULL;) {
    s[1][i] = atoi(number);
    number = strtok(NULL, " ");
    i += 1;
}

关于C 如何输入以空格分隔的值(战舰游戏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29435874/

相关文章:

c - U-boot 中的 wait_event_timeout 等效项

c - (ARDUINO) 关于端口操作

c - 试图在 c 中打印一行文本文件

c - DEV C++ 头文件列表

在 C 中创建文本中的数字数组

c++ - 将 double* 转换为 float*

c - 在 Unix 上执行共享库

c - 我自己的 printf 怎么能和原来的 printf 做同样的一轮呢?

c - libcurl 不适用于 http 重定向

c++ - opencv houghCircles ( .... ?PARAM1?, ?PARAM2?)