【发布时间】:2013-10-20 03:03:15
【问题描述】:
想从文件“Hello.cpp”中一次填充一行。但是,如果我按照以下方式执行此操作,我会填充整个文件 [w] 次,而不是只为 i 的每次迭代从文件中抓取一行。
如果我从 getline 中删除 { },则数组将填充最后一行 "Hello.cpp" [w] 次。
我不确定如何每次从 Hello.cpp 文件中获取新的 [i]。
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
int w=0;
ifstream in("Hello.cpp");
string s;
while(getline(in, s))
w=w+1; //first count the number of lines in the file for the array
string a[w];//make an array big enough for the file
for(int i = 0; i < w ; i++) {
ifstream in("Hello.cpp");
string s;
while(getline(in, s)){
a[i] = s;
cout << i + 1 << " " << s << endl;
}
}
【问题讨论】:
-
那不是有效的 C++。您需要一个编译时常量作为数组大小。通常,如果没有自定义行迭代器,这是通过在读取行时将行推到向量上来完成的。
-
1.计算行数 2. 创建 C 样式的数组来保存行...它必须是一个数组吗?
标签: c++