如何将名称读入指针数组并输出它们

How to read names into a pointer array and output them?

本文关键字:数组 输出 指针      更新时间:2023-10-16

这是我到目前为止得到的:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int characterList = 0;
    char* dynamo = new char[1000];
    char* buffer = dynamo;
    ifstream input("wordlist.txt");
    if (input.is_open())
    {
        input >> dynamo[characterList];
        while (input.eof())
        {
            characterList++;
            input >> dynamo[characterList];
            cout << dynamo[characterList];
        }
    }
    else
    {
        cout << "File not opened" << endl;
    }
    return;
}

我是初学者,所以如果这看起来像是糟糕的编码练习,我深表歉意。我创建了一个文本文件,其中包含比尔·科斯比(Bill Cosby)的引文,我试图一次读一个单词。这句话是"我不知道成功的关键,但失败的关键是试图取悦所有人。我试图从忽略标点符号的文本文档中一次阅读一个单词。我知道有很多类似的问题,但他们使用的是我没有学过的代码,所以我很抱歉有一个重复的问题。我没有学到getline(我曾经cin.getline)和#include <string>.

编辑:我忘了提,所以我很抱歉没有早点这样做,但我正在研究动态内存分配,这就是我使用新字符[1000]的原因。

我建议您使用std::string,而不是使用 new[] 手动在堆上分配缓冲区并尝试手动将文本从文件中读取到这些缓冲区中(并且不要忘记通过适当的delete[]调用释放缓冲区!

C++像std::ifstream这样的输入流类可以简单地将文本读入std::string实例,这要归功于适当的重载operator<<
语法非常简单:

    string word;
    while (inFile >> word)
    {
        cout << word << endl;
    }

下面是一个完整的可编译示例代码,供您试验和学习:

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
    ifstream inFile("test.txt");
    if (inFile.is_open())
    {
        string word;
        while (inFile >> word)
        {
            cout << word << endl;
        }
    }
    else
    {
        cout << "Can't open file." << endl;
    }    
}

这是我在测试文本文件上获得的输出,其中包含您的问题中指定的内容:

I
don't
know
the
key
to
success,
but
the
key
to
failure
is
trying
to
please
everybody.

注意

当然,一旦你把你的单词读到一个std::string实例中,你可以将它们存储在一个容器中,比如std::vector<std::string>,使用它的push_back()方法。

我会做这样的事情:

#include <iostream>
#include <string>
#include <fstream>
int main() {
  std::string array[6];
  std::ifstream infile("Team.txt");
  std::string line;
  int i = 0;
  while (std::getline(infile, line)) {
    array[i++] = line;
  }
  return 0;
}

基于这个答案。

在这里,我们假设我们必须从文件"Team.txt"中读取 6 行。我们使用 std:::getline() 并放入一个while,以便我们读取所有文件。

在每次迭代中,line 都会保存读取文件的当前行。在体内,我们将其存储在 array[i] .