【问题标题】:Fill an array with getline loop用 getline 循环填充数组
【发布时间】: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++


【解决方案1】:

我会在重新打开之前关闭您的文件(最佳做法)。

在我看来,您需要将文件打开(ifstream 构造函数)移到 for 之外(您真的想打开文件 w 次)吗?既然您费心先数行数,您是否真的想要这样的东西:

ifstream in1("Hello.cpp");
for(int i = 0; i < w ; i++) {
    getline(in1, a[i]);
    cout << i + 1 << " " << a[i] << endl;
 }

【讨论】:

    猜你喜欢
    • 2020-09-11
    • 2021-04-21
    • 2014-04-09
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多