美好的一天。我如何逐行读取文件并将其放入数组中遇到了很大问题。我们被要求使用此命令行参数从文本文件中获取所需的数据。
program.exe < input.txt
并且input.txt如下所示:
4 4
*...
....
.*..
....
我将如何解析这个整数将分别是行和列的值,以及&#34; *&#34;和&#34;。&#34;应该进入2D阵列?谢谢你的答案。
答案 0 :(得分:0)
您只需使用两个int
来存储行数和列数,并使用std::vector
std::string
来存储字符。
代码:
using namespace std;
int main()
{
int row, col;
cin>>row>>col;
vector<string> m(row);
for(int i = 0; i < row; ++i)
cin>>m[i];
}
由于您不知道需要输入多少个字符表,这里是更新的代码。 代码:
using namespace std;
int main()
{
int row, col;
//This is where your main data is stored.
vector<vector<string> >m;
//This will terminate if EOF is encountered.
while (cin >> row)
{
cin>>col;
//A temporary vector to enter your data.
vector<string> temp(row);
for (int i = 0; i < row; ++i)
{
cin>>temp[i];
}
m.push_back(temp);
}
//Do what you want with 'm'.
//You can access the nth instance using m[n-1].
}