如何使用C ++访问文本文件中的特定值 [英] How to access a specific value in a text file using C++

查看:70
本文介绍了如何使用C ++访问文本文件中的特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文本文件具有此结构和此值

my text file has this structure and this values

15.32 15.00 14.58 14.36 17.85 01.95 15.36 
14.58 21.63 25.00 47.11 48.95 45.63 12.00
74.58 52.66 45.55 47.65 15.55 00.23 78.69

每个列都是不同的类型数据,第一列是weight,第二列是size等等。例如,用户要求
的重量,该重量将是第一列

each column is a different type of data, the first column is weigh , second is size and so on. the user requests for instance the weight, which would be the first column

15.32
14.58
74.58

我需要打印

reg 1 reg 2 reg 3
15.32 14.58 74.58

此外,用户可以请求其他列,但我不知道我该怎么完成
i只能打印第一行

also, the user can request other column i don't know how i can accomplish this i am able only to print the first line

15.32 15.00 14.58 14.36 17.85 01.95 15.36 

使用此代码,但仅当我使用整数文件,如果它们是两倍,则下面的代码什么都不做

using this code, but only if i use integer files, if they are double the below code does nothing

string nextToken;
while (myfile>> nextToken) {
    cout << "Token: " << nextToken << endl;
}

但我不知道如何在列和行之间移动

but i don't know how to move between columns and lines

我正在使用此结构

struct measures{
    string date;
    double weight;
    double size;
    double fat;
    double imc;
    double chest;
    double waist;
} dataclient;

我读取这样的值

ofstream file;
file.open (dataclient.id, ios::out | ios::app);
if (file.is_open())
{
    cout<<"   ENTER THE WEIGH"<<endl;
    cin>>dataclient.weigh;
    file<<dataclient.weigh<<" ";

    cout<<"   ENTER THE SIZE"<<endl;
    cin>>dataclient.size;
    file<<dataclient.size<<" ";

    cout<<"  ENTER  % FAT"<<endl;
    cin>>dataclient.fat;
    file<<dataclient.fat<<" ";

这可以为用户执行多次,然后关闭文件

this can be done several times for an user,and then closes the file

之后,用户请求任何值

推荐答案

一种更简单的方法是使函数具有两个参数:起始项和步幅,或每行的项数。然后,您可以跳过项直到开始项,然后跳过连续项之间的跨度:

An even easier way is to make a function with two parameters: the starting item and the "stride", or the number of items per row. You can then skip items until the starting item and then skip the stride between successive items:

void printcolumn(int start, int stride, ifstream &in)
{
  string nextToken;

  // skip until the start
  while(start-->0) in >> nextToken;

  // and then start writing the items
  while (in >> nextToken) 
  {
    cout << "Token: " << nextToken << endl;

    // and skip the stride
    for(int i=1;i<stride;++i) in >> nextToken;
  }
}

对于您的特定示例,您可以这样称呼它 printcolumn(0,7,myfile);

For your specific example, you'd call it like printcolumn(0, 7, myfile);

这篇关于如何使用C ++访问文本文件中的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆