How to print specific array entries from a .txt file in C ++?


First, I'm very new to coding in C++. So, I have a .txt file, with names and numbers--here's an example.

chris 5

tara 7

Sam 13

Joey 15

I would like to use this code to retrieve the names and numbers, but how does one print specific array entries instead of just the variables name and number (I want it to show the name and the number on the screen)?

#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";

You're writing out name and number, but those aren't the variables you've read. You've read array entries.

Getting it working as simply as possible just comes down to changing your cout lines to be:

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

No need for a std::vector, ther's nothing wrong with how you've done it.