首先,我对使用 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";
}
}
最佳答案
您正在写出 name
和 number
,但这些不是您读取的变量。您已经阅读了数组条目。
让它尽可能简单地工作归结为将 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/