从文件中读取不同的值类型 [英] Reading in different value types from file

查看:65
本文介绍了从文件中读取不同的值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一个看起来像这样的文件:

I want to read in a file that looks something like this:

Dom 69.5 1.80
Leigh 51.1 1.62



它必须在第一部分(名称)中读取为字符串,然后在第二部分中读取为浮点数.



It must read in the first part(the name) as a string, and the next two values as floats.

推荐答案

一种方法是使用sscanf
喜欢,
one way is to use sscanf
like,
char text[] = "Dom 69.5 1.80";
sscanf(text,"%s %lf %lf",&str, &d1, &d1);



strtok 之类的,



or strtok like,

char stringa[] = "Dom 69.5 1.80";
    char seps[]   = " ,\t\n";

   token = strtok( stringa, seps ); 
   
   // 1st one string
   printf( " %s\n", token );
      
   //2nd double
   token = strtok( NULL, seps ); 
   double d1 = strtod(token, NULL);
   printf( " %lf", d2);
   
   //3nd double
   token = strtok( NULL, seps );
   double d2 = strtod(token, NULL);
  printf( " %lf", d1);


C ++的方法是使用流,而不是C库函数.

像这样的东西:

The C++ way is to use streams, rather than the C library functions.

Something like this:

#include <string>
#include <fstream>
#include <vector>

// Data structure for a line from file
struct FileLine
{
  std::string name;
  float f1, f2;
};

// Reading a line from stream
FileLine ReadLine(std::istream& in)
{
  FileLine line;
  in >> line.name >> line.f1 >> line.f2;
  return line;
}

void ReadFile()
{
  // Open stream from data file
  std::ifstream in("datafile.dat");
  // Read stream
  while (!in.eof())
  {
    FileLine l = ReadLine(in);
    // do whatever
  }
}


这篇关于从文件中读取不同的值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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