C++ 按列读取文本文件并显示所有列值数组
我正在尝试按列读取文件。主要功能是我的文件应该显示所有值中的一列。 我试着用向量来做C++ 按列读取文本文件并显示所有列值数组,c++,file,io,C++,File,Io,我正在尝试按列读取文件。主要功能是我的文件应该显示所有值中的一列。 我试着用向量来做 void search(){ const int COLUMNS = 4; vector< vector <int> > data; string filename = "bla.txt"; ifstream ifile(filename.c_str()); if (ifile.is_open()) { int num;
void search(){
const int COLUMNS = 4;
vector< vector <int> > data;
string filename = "bla.txt";
ifstream ifile(filename.c_str());
if (ifile.is_open()) {
int num;
vector <int> numbers_in_line;
while (ifile >> num) {
numbers_in_line.push_back(num);
if (numbers_in_line.size() == COLUMNS) {
data.push_back(numbers_in_line);
numbers_in_line.clear();
}
}
}
else {
cerr << "There was an error opening the input file!\n";
exit(1);
}
//now get the column from the 2d vector:
vector <int> column;
int col = 2;//example: the 2nd column
for (int i = 0; i < data.size(); ++i) {
column.push_back(data[i][col - 1]);
cout << column[i] << endl;
}
ifile.close();
}
这段代码可以编译,但我并没有得到控制台中显示的任何值。当我试着调试最后一行时,它不会被缓存,所以我猜他们什么也不做
从不输入循环,因为num
是int
,输入行的第一个元素是John
,不能解释为int
,因此ifile
被设置为错误状态,循环条件立即为false
最简单的解决方法是首先使用std::getline
读取整行,然后标记生成的std::string
,例如使用std::istringstream
然后,可以使用类似于
std::stoi的函数将该标记化产生的单个std::string
标记转换为适当的类型,并确保每个步骤都是正确的
阅读每一行,然后打印出来,以确保你做得正确
您需要拆分每一行。在这一步之后,您将使用John、1990等作为字符串李>
现在将2-4列转换为整数李>
每个步骤都有很好的解决方案,您可以很容易地找到。您打算将John
和Peter
存储在vector
中,而如果设置了ifstream的失败位,则您将退出循环。既然data.size()
等于0,就不会输出任何内容。如何使其成为多类型向量?@NotsoPr0:这是一个完全不同的问题。因此,你应该在这里提出一个新问题或搜索现有问题。提示:类似于boost::any
的东西可能会有帮助。我有点困惑,如何完成这3个步骤。如何拆分为列。也许你可以给我一些提示?为什么你这么想把你的列表错误地标记为代码?@NotsoPr0只需复制粘贴链接中的代码。然后将该函数调用为vector myvec=split(行“”)
。这将用空格分割,您将有一个vector
您迟早需要转换为int
的向量,因为它们非常有用。它类似于阵列,但具有更多功能。我打赌你可以在一个小时内学会它的大部分内容
John 1990 1.90 1
Peter 1980 1.88 0
...
while (ifile >> num) {