【问题标题】:Flag controlled while loop to search txt file标记控制 while 循环以搜索 txt 文件
【发布时间】:2016-05-25 18:17:47
【问题描述】:

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

【问题讨论】:

  • 您可能希望首先发布您的代码,以便我们在向您描述解决方案时有一个参考框架。
  • 描述很简单,所以如果你有一些具体的问题,请询问。在一个循环中,读取每一行,如果该行以您要搜索的内容开头,则输出该行 # 之后的所有内容。
  • 感谢您发布家庭作业的副本,然后附上您的答案。不幸的是,您似乎已将答案提交给 stackoverflow.com 而不是您的讲师。 stackoverflow.com 不是一个对教师课程进行评分的网站,而是用于提问和获取答案的网站。如果你有一个与你的家庭作业有关的问题,你应该明确地写出它是什么,而不是仅仅发布你的代码,让每个人都猜测你的问题是什么。

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


【解决方案1】:

以下变量只能包含一个字符。

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
}

【讨论】:

  • 为什么选择使用格式'std::'而不是'using namespace std;'?
  • 我通常使用多个命名空间,我想知道我正在使用哪个库中的哪个函数,以及显而易见的一个:避免名称冲突。
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多