文件读取和向量条目的问题
Issue with file reading and vector entries
这个程序的目的是读取一个文本文件并将其内容存储在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);
}
相关文章:
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 添加存储在向量中的大整数的函数出现问题
- 尝试将向量初始化为类成员时出现问题
- 在将字符串放入字符串向量时遇到问题?
- 取消引用向量时出现问题
- 在C++中对结构向量进行排序时出现问题
- 在 c++ 中创建和访问 4D 向量时出现问题
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 使用指针向量(带代码)C++(以及对其使用的便利性的怀疑)时出现问题
- C++ 继承向量问题(无限循环+在其他类中使用向量的问题)
- 在 c++ 中访问列表向量时出现问题
- c++向量push_back问题
- shared_ptr类的向量的向量初始化问题
- SWIG c++到python:向量问题
- 在 Rcpp-Function 中使用布尔向量的子集(Rcpp 初学者的问题..)
- 无法取消引用超出范围的向量迭代器 - 有什么问题?
- 在构造函数中更新指针向量时出现问题
- 在使用 std::sort() 和 lambda 函数按属性对 ADT 的向量进行排序时遇到问题
- 为什么C++在自定义结构向量时会出现 ostream 重载问题?
- C++:问题向量 STL.