我是一名C++初学者,尝试创建一个程序来跟踪每个服务员在酒吧中服务的产品。其中一部分是从文本文件中读取价格。如何从C++文件的特定行中提取数字(浮点数)?
每行是一个特定产品的价格。
用户应该输入产品“代码”,这实际上是已经服务的产品线(所有这些将在一个循环中,因为许多产品将被送达)。
当用户输入一个数字,比如说5,我如何从文本的第5行中获得价格?
也许有一种方法可以在程序启动时将文件导入数组,但我不知道该怎么做。
更新: 我终于修复了代码错误,但我真的不满意我的程序。就我而言,当它问Y/N特价时,我只输入特价,它解释为“NO”。此外,我现在希望它记录每个服务员获得的总金额,并且每个服务员都有一个与其他人相似的文本文件名(例如,第一个服务员的姓名位于waiters.txt的第一行,并继续。 ...),但根据当天的情况,只有4-5名服务员。如何扩展程序而无需从头开始?
我自己解决了。要从文件中获取行,请使用此代码
char product_names[101][15];
fstream file("prices.txt");
for(int i = 1; i <= 100; ++i)
{
file >> product_prices[i];
}
fstream file2("names.txt");
for(int i = 1; i <= 100; ++i)
{
file >> product_names[i];
}
以下是整个程序的最终代码,欢迎对可能的改进发表评论。
#include <iostream>
#include<windows.h>
#include<iostream>
#include<fstream>
#include<iomanip>
#include <string>
using namespace std;
int main()
{
float sum[9]={0,0,0,0,0,0,0,0,0};
float product_prices[101];
int code;
float total;
char waiter_name[9][15];
float price;
int wc;
cout <<"How many waiters are there? \n";
int w; // Maximum 9 waiters
cin >> w;
for (int i=1; i<=w; ++i)
{cin >>waiter_name[i];}
string a;
char product_names[101][15];
fstream file("prices.txt");
for(int i = 1; i <= 100; ++i)
{
file >> product_prices[i];
}
fstream file2("names.txt");
for(int i = 1; i <= 100; ++i)
{
file >> product_names[i];
}
ST:
while (true)
{ cout << "Please give product code or type -1 when you're done. \n";
cin >> code;
if (code==-1) break;
cout << "Please give the waiter's code. \n";
cin >> wc;
price=product_prices[code];
cout <<"Default price is " << price << " . Type Y/N if you want to make a special price or A to chose another product or waiter\n";
cin >> a;
if (a=="Y"||a=="y") { cin >> price; }
else if (a=="A" || a=="a") {goto ST;}
sum[wc]+=price;
cout << waiter_name[wc] <<" : " <<sum[wc] <<"\n";
}
for (int i=1; i<=w; ++i)
{
cout << waiter_name[i] <<" : " <<sum[i] <<"\n";
total+= sum[i];
}
return 0;
}
也@ArchbishopOfBanterbury我没想到你只是写这整个程序。但是,我不明白缓冲区的作用,我只有一个product_prices.txt和一个product_names.txt,产品代码是该行的编号。至于未经测试的代码,它远远超出我的知识水平,我甚至不知道如何使用地图。不过谢谢你。
产品价格放置在文件中,一个在另一个之下。名字也以这种方式存储。例如,第一个产品的名称位于product_names.txt的第一行,它的价格位于product_prices.txt的第一行。
您在请求用户输入之前解析文件。将所有价格保存在'std :: vector'中。 – StoryTeller
你的问题非常广泛,你能否请你张贴一些你试过的代码,以及你被困在哪里? –
格式很糟糕。为什么你有没有“goto”的标签? –