【问题标题】:How to infile/store first word of line as one variable, rest of line as another如何将行的第一个单词作为一个变量输入/存储,将其余行作为另一个变量
【发布时间】:2019-09-19 03:30:10
【问题描述】:

我有一个文本文件我想读入并存储在这里:

5

chrestomathy A selection of passages from an author or authors, designed to help in learning a language

detectable Able to be discovered or identified

feldspar An abundant rock-forming mineral typically occurring as colorless or pale-colored crystals

haricot A bean of a variety with small white seeds, especially the kidney bean

pluripotent Capable of giving rise to several different cell types

每一行都是一个单词,后面跟着它的定义,大写字母开始定义。我不知道如何在单独的变量中输入/存储单词和定义,因为它们都是字符串。

我在下面创建了一个模板化地图类:

template <typename Domain, typename Range>
class Map
{

public:
Map(int n); // number of entries in the table

~Map();

void add(Domain d, Range r); // add an entry to the table

bool lookup(Domain d, Range& r);

private:
int numEntries;

Domain* dArray;

Range* rArray;


};

这个“字典”应该是这个 Map 的一个实例,其中单词是域,范围是定义。

Executive::Executive(string file1)
{
int n;  

Map<string, string> Dictionary;

ifstream inFile1; 
inFile1.open("Dictionary0.txt");

inFile1>>n; 

for(int i=0; i<n; i++)
{

    //Dictionary.add(word, def);
    //Feel like i need to use something like this too but not sure how

}

}

我想读取和存储这些值,以便以后可以使用查找函数来检查单词是否在“字典”(文件)中,然后打印其定义。我创建了一个执行类来读取和存储。

【问题讨论】:

    标签: c++ class oop templates


    【解决方案1】:

    第 1 步:使用&gt;&gt; 将第一个单词读入std::string

    std::string word;
    inFile >> word;
    

    第 2 步:跳过单词后的空格:

    inFile >> std::skipws;
    

    第 3 步:使用std::getline 读取该行的其余部分:

    std::string definition;
    std::getline(std::cin, definition);
    

    【讨论】:

      猜你喜欢
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 2019-05-08
      相关资源
      最近更新 更多