【问题标题】:C++: Trying to read from a file line by line, saving into a vector and then printing the vector prints nothingC ++:尝试逐行读取文件,保存到向量中,然后打印向量什么也不打印
【发布时间】:2017-08-05 19:02:19
【问题描述】:

我正在尝试从文件中读取数据并将数据插入到向量中。该文件如下所示:

16
0100
0111
0111
0001
0100
1011
1010
0010
0110
1001
1100
1001
1100
0101
0101
0001

我希望我的矢量看起来像:

16 0 1 0 0 0 1 1 1 0 1 1 1...

我的代码如下所示:

void readFile(string name){
    ifstream fin;
    vector<int> graphData;
    int y;
    fin.open(name);
    if (!fin.is_open()){
        cout << "Error: Could not open data.";

    }
    else{
        while(!fin.eof()){
            fin >> y;
            graphData.push_back(y);
        }

    }
    fin.close();
    for(int i = 0; i < graphData.size(); ++i){
        cout << graphData[i] << " ";
    }
}

我很确定问题出在我定义 y 然后尝试将其推入。但是当我运行代码时,没有任何输出,就像向量为空一样。

【问题讨论】:

  • 与问题无关:在这种情况下使用 try 和 catch,它总是有帮助的
  • 我的意思是使用 getline
  • 输出也会是:"16 0100 0111 ..." 不是你指定的
  • 我可以在输出为 16 0 1 0 0 0 1 1 1 0 1 1 1 的地方得到它...我希望每个数字都在自己的索引中

标签: c++ vector ifstream


【解决方案1】:

您可以在跳过行数之后读取每个单独的字符并将其与'0''1' 进行比较。见以下代码:

int main() {

    vector<bool> bits;
    ifstream f(DATAFILE);
    if (f.is_open()) {
        int dummy;
        f >> dummy;
        char c;
        while (f >> c) {
            if (c == '1') {
                bits.push_back(true);
            }
            else if (c=='0') {
                bits.push_back(false);
            }
        }
        f.close();
        for(int i = 0; i < bits.size(); ++i){
            cout << bits[i] << " ";
        }
    }
    return 0;
}

【讨论】:

  • 这对我很有用。我想我可以从这里继续我正在做的事情。感谢您的帮助
  • 不客气;如果它解决了您的问题,请接受答案。
【解决方案2】:

尝试将数字读取为字符串:

unsigned int quantity = 0;
fin >> quantity;
fin.ignore(100000, '\n');
std::string number_text;
vector<int> binary;
while (getline(fin, number_text))
{
  for (int i = 0; i < number_text.length())
  {
    int bit = number_text[i] - '0';
    binary.push_back(bit);
  }
}

【讨论】:

    【解决方案3】:

    您应该使用 getline 函数逐行获取输入: 在fin.open(name);之后

    这样做:

    getline(fin,line);
    

    然后将line 保存到您的 y

    猜你喜欢
    • 1970-01-01
    • 2018-01-06
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 2012-11-01
    • 1970-01-01
    相关资源
    最近更新 更多