gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:20:44 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com