视觉C++.如何从文件中读取并与输入匹配

visual C++. how to read from file and match with input

本文关键字:输入 读取 C++ 文件 视觉      更新时间:2023-10-16

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

我有一个文本文件(水果.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;
       }
}

请告知谢谢。

在循环中,getline第一次循环line"apple",第二次读line "30nbanana",依此类推。

而是阅读整行(使用 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
        }
    }
}

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

  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();
}

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