如何将文件逐行读取到矢量中,然后打印矢量
How to read a file line-by-line into a vector and then print the vector
我正在尝试读取文件,将每一行添加到一个向量中,然后打印向量。 但是现在,它只会打印第一行。因此,我假设第一行是添加到向量中的唯一行,但我无法弄清楚原因。
这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
std::vector<std::string> vecOfStrs;
std::ifstream fileIn("example.txt");
std::string str;
std::string newLine;
newLine = str + "n";
while (std::getline(fileIn, str)) {
std::string newLine;
newLine = str + "n";
if (newLine.size() > 0) {
vecOfStrs.push_back(newLine);
}
fileIn.close();
for (int i = 0; i < vecOfStrs.size(); i++) {
std::cout << vecOfStrs.at(i) << ' ';
}
}
}
这是文本文件,现在它应该完全按照此处显示的方式打印出来:
Barry Sanders
1516 1319 1108 1875 -999
Emmitt Smith
1892 1333 1739 1922 1913 1733 -999
Walter Payton
1999 1827 1725 1677 -999
读取循环内部有一些逻辑真正属于循环完成后:
-
您在读取第一行后
close()
文件流,从而在第一次迭代后中断循环。
将 每行添加到
vector
后,您将打印整个。
此外,您根本不需要newLine
变量。
试试这个:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main() {
std::vector<std::string> vecOfStrs;
std::ifstream fileIn("example.txt");
std::string str;
while (std::getline(fileIn, str)) {
if (str.size() > 0) {
vecOfStrs.push_back(str);
}
}
fileIn.close();
for (size_t i = 0; i < vecOfStrs.size(); i++) {
std::cout << vecOfStrs[i] << ' ';
}
return 0;
}
相关文章:
- 我编写了以下代码来读取C++矩阵,然后打印其行和列.我收到此错误
- 读取一组用户输入,按升序排序,然后打印结果
- 如何在循环中使用scanf,将值存储到一个变量中,然后打印出来?
- 如何将文件逐行读取到矢量中,然后打印矢量
- 如何打印第一个和最后一个元素的和,然后打印第二个和倒数第二个元素的总和,依此类推
- C++ 如何创建 2D 数组,将其传递给另一个函数,然后打印
- 在结构向量中搜索一个数据成员,然后打印匹配的所有数据成员
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- 尝试将二进制数组转换为十六进制C++然后打印结果
- 如何将一个数组的每个元素与另一个元素进行比较(如果存在),然后打印是,否则否
- 带有用户输入的C 文本数组,然后打印输入
- 如何在文件中搜索关键字,然后打印其中包含的字符串
- 从文件中读取结果数据,加载它,比较它,然后打印显示
- 将结果存储在 C++Map 中,然后迭代它,然后打印出来
- 如何将结果存储在 Map 中 C++,然后迭代它,然后打印出结果
- 用"*"(特殊字符)初始化向量,然后打印出来
- 如何用自己的值填充tm结构,然后打印出来
- 按字母顺序降序对列表进行排序,然后打印列表
- 在c++中找到文本中的单词,然后打印下一个特定的行
- 如何修改以下代码,以便我实际上将文件的内容读入数组,然后打印出数组?