初学者,尝试将输入读入2d char数组。
输入文件格式为:,,, a,a,a,a ,,,'\ n',,,,,,,,,
需要在一个10乘10的数组中,总是有9个逗号而且没有空格,这就是为什么我有二十二的const int,以防有一个“船”占位符占用空间,在字符中有问题阅读,当我做阅读它会跳过所有其他角色。
任何帮助,将不胜感激。
#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;
}
答案 0 :(得分:0)
试试这段代码:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
string filename;
ifstream inputfile;
int rowcount= 0, colscount=0;
const int max_rows=20, max_cols=20 ;
char boardarray[max_rows][max_cols];
int main()
{
cout<< "input your battlestation board filename: " << endl;
cin >> filename;
inputfile.open(filename.c_str(), ios::in | ios::binary);
while(!inputfile)
{
cout << "file did not oipen please retry";
cin >> filename;
inputfile.open(filename.c_str(), ios::in | ios::binary);
}
while(!inputfile.eof())
{
char ch = 0;
colscount = 0;
while( ch!= '\n' && !inputfile.eof())
{
inputfile.read(&ch, 1);
if (ch != '\r' && ch!='\n') {
if (ch != ',') {
boardarray[rowcount][colscount] = ch;
} else {
colscount++;
}
}
}
rowcount++;
colscount++;
}
inputfile.close();
for(int i=0; i < rowcount; i++)
{
for(int j=0; j< colscount; j++)
{
cout << boardarray[i][j];
if(j == (colscount-1))
cout << endl;
}
}
}