c++ - 标志控制 while 循环搜索 txt 文件

标签 c++ if-statement while-loop flags

给定一个包含此数据的 .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
}

关于c++ - 标志控制 while 循环搜索 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35399188/

相关文章:

c++ - 使用 gzip 编写 gzip 文件

c++ - 在不透明物体内部绘制透明物体

javascript - JavaScript 函数中的 if 语句不起作用

java - 使用 If 或 Switch 语句更改交通信号灯

Java - For 循环(do/while)无限重复

python - 在 python 中计算余弦而不导入数学

c++ - 函数后的 const 如何优化程序?

c++ - g++/clang 覆盖特定函数的链接器

javascript - 在javascript中的if语句中定义变量

c - 为什么我在运行代码时收到调试断言失败错误