如何将名称读入指针数组并输出它们
How to read names into a pointer array and output them?
这是我到目前为止得到的:
#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]
.
- 将值从二维数组输出到文本文件
- 为什么我的数组输出一个不在其中的元素
- 长度为 20 的 Cout'ing 数组输出 23 个字符
- 将矢量数组输出到 tex 文件中,错误
- 来自不同位置的数组输出的执行时间
- 数组输出中缺少字符
- 字符数组输出 - C++
- C 合并的数组输出错误
- 制作垫子类型对象的数组.输出窗口显示同一帧
- C++数组输出地址
- 字符数组输出正确,但实际上没有存储正确的值
- 字符串数组输出
- 为什么在将字符数组输出到控制台时会得到垃圾值
- 字符数组输出额外的字符
- 从字符数组输出到控制台
- 为什么计数从字符数组输出错误的字符
- 动态初始化的 2D 数组输出错误
- C++指针和2d数组输出
- c++中奇怪的char数组输出
- 类函数中的c++字符数组输出