c++ - 如何在 C++ 中打印 .txt 文件中的特定数组条目?

标签 c++ arrays text-files

首先,我对使用 C++ 进行编码非常陌生。 所以,我有一个包含名称和数字的 .txt 文件——这是一个示例。

克里斯 5

度母 7

山姆 13

乔伊 15

我想使用这段代码来检索姓名和号码,但是如何打印特定的数组条目而不仅仅是变量名称和号码(我希望它在屏幕上显示姓名和号码)?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
string name;
int number;
struct sEntry
{
    std::string name;
    int number;
};
sEntry entries[256];
std::ifstream fin("input.txt"); // opens the text file
int nb_entries; // Keeps track of the number of entries read.

for (nb_entries = 0; fin.good() && nb_entries < 256;  nb_entries++) // Keep going until we hit the end of the file:
{
    fin >> entries[nb_entries].name;
    fin >> entries[nb_entries].number;
    cout << "Here, "<< name <<" is name.\n";
    cout << "Here, "<< number <<" is number.\n";
}
}

最佳答案

您正在写出 namenumber,但这些不是您读取的变量。您已经阅读了数组条目。

让它尽可能简单地工作归结为将 cout 行更改为:

cout << "Here, " << entries[nb_entries].name << " is name.\n";
cout << "Here, " << entries[nb_entries].number << " is number.\n";

不需要 std::vector,您的做法没有任何问题。

关于c++ - 如何在 C++ 中打印 .txt 文件中的特定数组条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10789392/

相关文章:

python - 如何使用Python根据ascii顺序移动字符

javascript - JS - 从所有数组数据创建动态 url(数组长度不固定)

python - 将元组列表写入文本文件并读回列表

c++ - 二进制通用 lambda 不匹配 ptr 到函数参数?

c++ - Qt (QFtp) 问题

c++ - 为什么右值 STL 容器中的元素 getter 返回左值?

c++ - QObjects 移入 QThreads 后信号不再工作

c - 使用多维数组的用户提示代码

php - php 中的 a+(读取/追加)与 a(追加)有何不同

c程序将ipconfig保存在文件中