首页 > 解决方案 > 我想将文件中的内容显示到控制台我该怎么做?

问题描述

我编写此代码是为了在文件中查找一个单词并借助 知道它的位置tellg(),但是我没有得到想要的输出来显示它。

这是我的代码:

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    fstream file;
    string filename="stockk.txt";
    file.open(filename.c_str());
    string pro_name;
    cout<<"Enter the product name you want to display : ";
    cin>>pro_name;
    int flag=0;
    int pos=0;
    while(!file.eof()){
        file>>pro_name;
        cout<<pro_name<<endl;
        if(pro_name=="maaza"){
            flag=1;
            pos=file.tellg();
            break;
        }
    }
    
    if(flag==1){
        cout<<"product name matched\n";
        cout<<pos<<endl;
        // delay(1000);
        // system("cls");
        file.seekg(pos-4,ios::beg);
        while(!file.eof()){
            file>>pro_name;
            cout<<pro_name<<endl;
        }
    }
    if(flag==0){
        cout<<"Go Home\n"; 
    }
    return 0;
}

这是我的txt文件

Name : rasana
Cost : 300
Price : 400
Quantity : 5
         
Name : maaza
Cost : 300
Price : 400
Quantity : 1

Name : oats
Cost : 300
Price : 5000
Quantity : 1

Name : nutella
Cost : 300
Price : 5000
Quantity : 1

Name : jam
Cost : 300
Price : 5000
Quantity : 1

我想maaza在控制台上显示它的成本、价格和数量。谁能向我解释为什么这不起作用?

标签: c++

解决方案


我希望我的主要看起来像这样:

int main()
{
    std::fstream file("stockk.txt");
    Unit        unit;

    // Read the file one product at a time.
    while (file >> unit) {
        // If I have found the item I am looking for.
        if (unit == "maaza") {
            // then print it our.
            std::cout << unit;
        }
    }
}

所以会做这样的事情:

#include <string>
#include <iostream>
#include <fstream>
#include <sstream>

// Create a class to represent the thing you want to read
// from the file. This is your atomic piece of information.
class Unit
{
    // These are the properties of that atomic piece of information.
    std::string     name;
    int             cost;
    int             price;
    int             quantity;

    public:
        // I will leave you to add constructors if you need them


        // Add a simple swap function as that is useful in making
        // some code below simpler. But basically does an atomic
        // swap of two values.
        void swap(Unit& other) noexcept
        {
            using std::swap;
            swap(name,    other.name);
            swap(cost,    other.cost);
            swap(price,   other.price);
            swap(quantity,other.quantity);
        }
        friend void swap(Unit& lhs, Unit& rhs)   {lhs.swap(rhs);}


        // Need the ability to compare an object with a name.
        bool operator==(std::string const& testName) const   {return name == testName;}

        // External IO operators
        // We will use these to read/print objects from the file.
        // They simply call read/print methods on the object and return
        // the stream to allow for chaining.
        friend std::istream& operator>>(std::istream& str, Unit& data)
        {
            data.read(str);
            return str;
        }
        friend std::ostream& operator<<(std::ostream& str, Unit const& data)
        {
            data.print(str);
            return str;
        }
    private:

        // Read a single value from a file and check it is valid.
        // This is used by the main read() function below.
        template<typename T>
        T read(std::istream& str, std::string const& expectedPrefix)
        {
            // Steam read a line from the file and put it in
            // a stringstream. This makes it easy to handle for
            // processing of human readable text. Not worried if
            // it fails at this point as that will result in an empty
            // linestream which will fail at the next step.
            std::string     line;
            std::getline(str, line);    
            std::stringstream   lineStream(line);

            // Define the expected things you want from the line.
            bool            goodread = false;
            std::string     prefix;
            char            colon = '*';
            T               value{};

            // Try and read a line
            if (lineStream >> prefix >> colon >> value) {
                // Did we find what was expected.
                if (prefix == expectedPrefix && colon == ':') {
                    goodread = true;
                }
            }

            // If the read failed in some way
            // Then mark the stream as bad.
            if (!goodread) {
                str.setstate(std::ios::failbit);
            }

            return value;
        }
        void read(std::istream& str)
        {
            // Use a temporary value.
            // If the read works we will transfer to this.
            Unit    tmp;

            // Manually read each value.
            tmp.name    = read<std::string>(str, "Name");
            tmp.cost    = read<int>(str, "Cost");
            tmp.price   = read<int>(str, "Price");
            tmp.quantity= read<int>(str, "Quantity");

            // Ignore empty line
            std::string     line;
            std::getline(str, line);

            // If the read worked then swap this and the temporary value.
            if (str) {
                swap(tmp);
            }
        }
        void print(std::ostream& str) const
        {
            // Print the value in the same way that you would read it.
            str << "Name : "    << name     << "\n"
                << "Cost : "    << cost     << "\n"
                << "Price : "   << price    << "\n"
                << "Quantity : "<< quantity << "\n"
                << "\n";
        }
};

推荐阅读