【发布时间】:2012-12-27 13:39:48
【问题描述】:
我创建了一个 c++ 应用程序来将文件的内容读入数组:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream myfile;
myfile.open("myfile.txt");
int a[3];
int counter = 0;
char s[10];
while (!myfile.eof())
{
myfile.getline(s, 10,';');
a[counter]=atoi(s);
counter++;
}
for (int i = 0 ; i<3 ; i++)
cout << a[i]<<endl;
cin.get();
}
如果我的文件是:
15;25;50
一切正常
我的问题是: 如果我将文件更改为:
15;25;50
12;85;22
如何将所有文件读入 3*2 数组?
【问题讨论】:
-
好吧,我找不到任何方法:(
-
1.使用
std::string,而不是字符数组和std::vector,而不是在文件中有超过三行时溢出的数组。 2. 使用while (getline()),而不是while (!eof())。 3. 使用stoi代替atoi之类的东西,这绝对无法判断这是不是一个错误。 4. 更喜欢std::whatever而不是using namespace std;。 -
那么,您认为您需要做什么?如何定义一个 3 x 2 矩阵(二维数组)?
-
@Mats Petersson ,我将使用 int b[3][2] 定义它,我知道如何使用数组,问题是我找不到任何方法将文件内容复制到其中。
-
它遵循与您当前相同的方式。每行都需要一个循环...
标签: c++ file-io multidimensional-array