【发布时间】:2017-03-26 04:01:31
【问题描述】:
初学者,试图将输入读入二维字符数组。
输入文件格式为:,,,a,a,a,a,,, '\n' ,,,,,,,,,,
需要在 10 x 10 数组中,总是有 9 个逗号并且没有空格,这就是为什么我的 const int 为 20 以防万一有一个“船”占位符占用空间,在字符中读取有问题,当我这样做时阅读它会跳过所有其他字符。
任何帮助,将不胜感激。
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
bool checkship();
string filename;
ifstream inputfile;
int rowcount= 0, colscount=0;
const int rows=20, cols=20 ;
char boardarray[rows][cols];
int main()
{
cout<< "input your battlestation board filename: " << endl;
cin >> filename;
inputfile.open(filename.c_str());
while(!inputfile)
{
cout << "file did not oipen please retry";
cin >> filename;
inputfile.open(filename.c_str());
}
while(inputfile)
{
for(rowcount=0;rowcount < rows;rowcount++)
{
for(colscount=0; colscount < cols; colscount++)
{
char ch;
inputfile >> ch;
while( ch!= '\n')
{
inputfile >> boardarray[rowcount][colscount];
}
if(ch = '\n')
{ rowcount++;
colscount= 0;
}
} }
}
inputfile.close();
for(rowcount=0; rowcount <10 ; rowcount++)
{
for(colscount=0; colscount< cols; colscount++)
{
cout << boardarray[rowcount][colscount];
if(colscount == 9)
cout << endl;
}
}
return 0;
}
【问题讨论】:
-
文件的内容我不清楚。
inputfile >> boardarray[rowcount][colscount];如果文件中有任何空白字符,就会出现问题。