0

我正在尝试读取一个文本文件并将水果与我输入的内容进行匹配(例如,我输入 apple,它会在文本文件中搜索单词 apple 并将其匹配并输出它已找到)但我正在努力实现我的结果想要,因此需要帮助。

我有一个文本文件(fruit.txt),其内容如下所示

苹果,30

香蕉,20

梨,10


这是我的代码

string fruit;
string amount;
string line = " ";
ifstream readFile("fruit.txt");
fstream fin;

cout << "Enter A fruit: ";
cin >> fruit;

fin >> fruit >> amount;
while (getline(readFile, line,','))
    {
        if(fruit != line) {
            cout <<"the fruit that you type is not found.";
        }

       else {
           cout <<"fruit found! "<< fruit;
       }
}

请指教谢谢。

4

2 回答 2

0

我首先要说我只是像你一样的初学者,拿了你的代码并做了一些改变,例如:

  1. 使用“fstream”从文件中读取,直到不是文件的结尾。

  2. 然后将每一行读入字符串流,以便稍后使用逗号分隔符将其制动。

  3. 我还使用了一个二维数组来存储水果和每种类型的数量。

  4. 最后,我不得不在数组中搜索我想要展示的水果。

在发布代码之前,我想警告您,如果有超过 20 种水果具有多个属性(在本例中为数量),该程序将无法运行。这是代码:

#include <sstream>
#include <fstream>
#include <iostream>
#include <stdio.h>
using namespace std;

void main  (void)
{
    fstream readFile("fruit.txt");
    string fruit,amount,line;
    bool found = false;
    string fruitArray[20][2];

    cout << "Enter A fruit: ";
    cin >> fruit;

    while (!readFile.eof())
    {
        int y =0 ;
        int x =0 ;
        getline(readFile,line);
        stringstream ss(line);
        string tempFruit;
        while (getline(ss,tempFruit,','))
        {
            fruitArray[x][y] = tempFruit;
            y++;
        }
        x++;
    }

    for (int i = 0; i < 20; i++)
    {
        for (int ii = 0; ii < 2; ii++)
        {
            string test = fruitArray[i][ii] ;
            if  (test == fruit)
            { 
                amount = fruitArray[i][ii+1];
                found = true;
                break;
            } 
            else{
                cout <<"Searching" << '\n';
            } 
        }
        if (found){
            cout << "Found: " << fruit << ". Amount:" << amount << endl;
            break;
        }
    }
    cout << "Press any key to exit he program.";
    getchar();
}

希望你从中学到了一些东西(我确实做到了)。

于 2013-10-08T15:21:27.753 回答
0

在循环中,getline您读"apple"line第一个循环,然后"30\nbanana"进入line第二个循环,依此类推。

而是阅读整行(使用getline),然后使用例如std::istringstream提取水果和数量。

就像是:

std::string line;
while (std:::getline(readFile, line))
{
    std::istringstream iss(line);

    std::string fruit;
    if (std::getline(iss, fruit, ','))
    {
        // Have a fruit, get amount
        int amount;
        if (iss >> amount)
        {
            // Have both fruit and amount
        }
    }
}
于 2013-10-08T10:06:02.810 回答