试图打开文件并用矢量逐字复制
Trying to open file and copy it word by word with vector
我正试图打开一个文件并逐字逐句地读取它。我不知道我的问题在哪里,因为打开文件后它似乎坏了。
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
#include <array>
using namespace std;
int main()
{
string path, test;
ifstream inputFile;
vector<string> words;
cout << "What is the path for the input file? ";
getline(cin, path);
inputFile.open(path, ios::in);
while (!inputFile.eof())
{
cin >> test;
words.push_back(test);
}
for (int i = 0; i < words.size(); i++)
{
cout << words.at(i) << endl;
}
inputFile.close();
return 0;
}
while (!inputFile.eof())
{
cin >> test;
words.push_back(test);
}
这里有两个问题:
您打开了
inputFile
,但随后尝试从std::cin
读取"while(!inputFile.of())"总是错误的做法。
这里还有第三个问题:
- 使用调试器会立即发现这两个问题。举个例子,我将编译后的代码加载到调试器中,并逐步进行调试。问题显而易见
@Sam有你做错的所有事情。
但是,使用循环的另一种选择就是使用迭代器来构建数组。
std::ifstream file(path);
std::vector<std::string> words(std::istream_iterator<std::string>(file),
std::istream_iterator<std::string>());
要打印出来,您可以使用复印件。
std::copy(std::begin(words), std::end(words),
std::ostream_iterator(std::cout, "n"));
目前,这将使用空格作为单词之间的分隔符来分隔单词。这意味着单词中将包含标点符号等。看看如何让流将标点符号视为空格:如何将标点符号分类为空格
感谢大家的帮助。这是最后的代码(对于将来在谷歌上搜索的人)
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
#include <array>
using namespace std;
int main()
{
string path, test;
ifstream inputFile;
vector<string> words;
cout << "What is the path for the input file? ";
getline(cin, path);
inputFile.open(path, ios::in);
while (inputFile >> test)
{
words.push_back(test);
}
for (int i = 0; i < words.size(); i++)
{
cout << words.at(i) << endl;
}
inputFile.close();
return 0;
}
相关文章:
- 复制文件流C++静态变量
- 如何递归复制文件和目录
- 复制文件的最佳方式是什么,以便我可以在复制过程中轻松取消复制?
- 复制文件成功,移动文件失败,参数相同 - C++
- 从 QProcess 复制文件夹的内容
- 以非常低的资源要求强制复制文件
- binding.gyp:如何使用"copies"部分在多个位置复制文件
- 如何在 Visual Studio 2015 中的构建结束时复制文件
- 自复制文件到新位置tchar不兼容
- 当我使用fs.rdbuf()复制文件时,我会丢失一些数据
- C++如何复制文件 * 指针
- 复制文件时是否可以自动创建不存在的目录?
- 复制文件时如何调用取消?(使用复制文件 ex 函数和复制进度例程回调函数)
- Linux复制文件连接到节点JS / Python / C / C 之后
- 使用C++在 Linux 中复制文件的有效方法
- 我可以在锁定文件后复制文件吗?
- 在线程中复制文件以防止冻结应用程序
- 如何使用libssh和SFTP在C/C++中复制文件
- 如何复制文件的二进制数据
- 使用 IFileOperation 复制文件 (C++)