试图打开文件并用矢量逐字复制

Trying to open file and copy it word by word with vector

本文关键字:复制 文件      更新时间:2023-10-16

我正试图打开一个文件并逐字逐句地读取它。我不知道我的问题在哪里,因为打开文件后它似乎坏了。

#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);
}

这里有两个问题:

  1. 您打开了inputFile,但随后尝试从std::cin 读取

  2. "while(!inputFile.of())"总是错误的做法。

这里还有第三个问题:

  1. 使用调试器会立即发现这两个问题。举个例子,我将编译后的代码加载到调试器中,并逐步进行调试。问题显而易见

@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;
}