簡體   English   中英

標志受控制,同時循環搜索txt文件

[英]Flag controlled while loop to search txt file

給定一個包含此數據的.txt文件(它可以包含任意數量的相似行):

hammer#9.95
shovel#12.35

使用C ++中的while循環控制的標志,當在導入的.txt文件中搜索商品名稱時,應返回商品的價格(由哈希分隔)。

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

using namespace std;

int main()
{


inFile.open(invoice1.txt);

char name;
char search;
int price;


ifstream inFile;
ofstream outFile;
bool found = false;

    if (!inFile)
        {
        cout<<"File not found"<<endl;
        }


outFile.open(invoice1.txt)

inFile>>name;
inFile>>price;

cout<<"Enter the name of an item to find its price: "<<endl;
cin>>search;

    while (!found)
    {


        if (found)
            found = true;

    }

cout<<"The item "<<search<<" costs "<<price<<"."<<endl;

return 0;
}

以下變量只能包含一個字符。

char name;
char search;

解決方法是將其替換為例如char name[30]; 此變量可以容納30個字符。

但是最好使用std::string因為它可以動態增長到任意大小。

std::string name;
std::string search;

您還打開同一文件兩次,一次具有讀取權限,一次具有寫入權限。 就您而言,您只需要閱讀它。 如果需要寫/讀訪問權限,則可以使用流標志std::fstream s("filename.txt",std::ios::in | std::ios::out);

這是您要完成的目標的完整示例:

std::cout << "Enter the name of an item to find its price: " << std::endl;
std::string search;
std::cin >> search;

std::ifstream inFile("invoice1.txt");

if (inFile) // Make sure no error ocurred
{
    std::string line;
    std::string price;

    while (getline(inFile, line)) // Loop trought all lines in the file
    {
        std::size_t f = line.find('#');

        if (f == std::string::npos)  // If we can't find a '#', ignore line.
            continue;

        std::string item_name = line.substr(0, f);

        if (item_name == search) //note: == is a case sensitive comparison.
        {
            price = line.substr(f + 1); // + 1 to dodge '#' character
            break; // Break loop, since we found the item. No need to process more lines.
        }
    }

    if (price.empty())
        std::cout << "Item: " << search << " does not exist." << std::endl;
    else
    {
        std::cout << "Item: " << search << " found." << std::endl;
        std::cout << "Price: " << price << std::endl;

    }

    inFile.close(); // close file
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM