文件读取和向量条目的问题

Issue with file reading and vector entries

本文关键字:问题 向量 读取 文件      更新时间:2023-10-16

这个程序的目的是读取一个文本文件并将其内容存储在3个单独的向量中。

名为"InsultsSource.txt"的文本文件包含50行以制表符分隔的形容词列,如下所示:

happy    sad    angry
tired    mad    hungry

下面是我用来实现这个的代码。由于某种原因,everything一直工作到第16行,此时返回空格。我已经检查了文本文件,看看格式是否在那里改变,但它看起来很好。我只是想知道是否有任何错误在我的逻辑/代码,导致这个问题。

#include <vector>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
    ifstream fileIn("InsultsSource.txt");
    vector<string> col1;
    vector<string> col2;
    vector<string> col3;
    string word;
    if (fileIn.fail()) {
        cerr << "Unable to open file" << endl;
    }
    for (int i = 0; i < 50; i++) {
        if (i % 3 == 0) {
            getline(fileIn, word, 't');
            col1.push_back(word);
        }
        else if (i % 3 == 1) {
            getline(fileIn, word, 't');
            col2.push_back(word);
        }
        else {
            getline(fileIn, word);
            col3.push_back(word);
        }
    }
    for(int j = 0; j < 50; j++) {
        cout << j+1 << " " << col1[j] << endl;
        //cout << "Thou " << col1[j] << " " << col2[j] << " " << col3[j] << "!" << endl;
    }
    return 0;
}

您正在阅读50个单词然后尝试从每列打印50个单词

去掉for循环,用while代替:

std::string text;
while (std::getline(fileIn, text, 't'))
{
  col1.push_back(text);
  std::getline(fileIn, text, 't');
  col2.push_back(text);
  std::getline(fileIn, text);
  col3.push_back(text);
}

这可能是你想用一个结构对每一行建模的情况。

struct Record
{
  std::string col1;
  std::string col2;
  std::string col3;
}
std::vector<Record> database;
Record r;
while (std::getline(fileIn, r.col1, 't')
{
  std::getline(fileIn, r.col2, 't');
  std::getline(fileIn, r.col3);
  database.push_back(r);
}

不如用

std::string val1, val2; val3;
vector<string> col1;
vector<string> col2;
vector<string> col3;
while(fileIn >> val1 >> val2 >> val3) {
    col1.push_back(val1);
    col2.push_back(val2);
    col3.push_back(val3);
}