C++ ifstream帮助(简单)

标签 c++ file input

我试图从 .txt 文件中获取一些名称并将它们添加到 char 数组中,但发生了一些奇怪的事情。这是我的代码输入部分:

int main()
{
string namelist[30];
int i=0;
string line;
ifstream file("C:\\names.txt");
if (file.is_open())
{
    while ( getline (file,line).good () )
    {
        getline(file,line);
        cout << line << endl;  // It prints the names normally (it was added for   debugging) //
        namelist[i] = line;
    }
    file.close();
}
cout << namelist;  // Here is the prob.

在代码的最后一行,它在控制台上打印了一个指针而不是列表,我 不知道为什么。 我是 C++ 的新手,所以不要无礼!

文本文件是这样的:

John
Nick
Samatha
Joe
...

任何帮助将不胜感激:)

最佳答案

因为数组名是指针,所以写成

for (int i = 0; i < 30; ++i)
    std::cout << namelist[i] << std::endl;

#include <algorithm>
#include <iterator>
//...
std::copy(namelist
         , namelist + 30
         , std::ostream_iterator<std::string>(std::cout, "\n")
);

关于C++ ifstream帮助(简单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12309659/

相关文章:

c++ - Vscode/C++ - cout 无法输出完整句子且无法与整数连接

python - 如果输入长度 > 20,则生成不同消息的子类方法

javascript - 如何用解析值覆盖输入字段?

linux - 我如何在 Linux 中执行单向差异?

c - 如何用 C 语言从文件中读取文本/数字

python - codecs.open 在特定路径Python中创建txt文件

缓冲区中的字符阻止整数输入

c++ - 仅专门化模板类的一个方法(的一部分)

c++ - 以原子方式访问存储在 map 中的资源

c++ - 换币 C++