gpt4 book ai didi

c++ - 文件读取和 vector 条目问题

转载 作者:行者123 更新时间:2023-11-28 00:00:02 24 4
gpt4 key购买 nike

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

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

happy    sad    angry
tired mad hungry

下面是我用来实现此目的的代码。出于某种原因,一切正常,直到第 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 个单词。

关于c++ - 文件读取和 vector 条目问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39860342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com