c++ - 如何将名称读入指针数组并输出?

标签 c++ pointers file-io cout

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

#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> .

编辑:我忘了提,所以我很抱歉没有早点这样做,但我正在研究动态内存分配,这就是我使用新的 char[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()方法。

关于c++ - 如何将名称读入指针数组并输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27826359/

相关文章:

有人可以帮我解释一下这个递归函数吗?

c - 从文本文件中删除一行?

javascript - 在nodejs中使用writeFile时未创建文件

c++ - 阿尔法()?或其他...调试断言失败,circlemud 游戏

c++ - 函数中的自动参数类型

c++ - 检查类型是否来自特定命名空间

c - argv 中指向字符串的指针是否可修改?

C++:试图将类作为类成员导入到另一个类中,但复制不正确

c - 释放空指针

c++ - C 和 C++ 标准库函数如何找到文件末尾?