如何使用以下格式解析字符串中的数据:1 Gt 500.85?

时间:2013-04-10 06:24:06

标签: c++ string file-io fstream

我有大约100行文字。每行都有以下格式:1 Gt 1.003 Gt将更改,长度为1到3个字符。如何解析此行并将Gt存储为字符串,将1.003存储为双精度,并丢弃1

2 个答案:

答案 0 :(得分:1)

很正常的东西。

ifstream file(...);
string line;
while (getline(file, line)
{
    istringstream buf(line);
    int dummy;
    string tag;
    double val;
    buf >> dummy >> tag >> val;
}

tag将为“Gt”,val将为1.003

答案 1 :(得分:1)

using namespace std;
int discardInt;
string strInput;
double dblInput;

vector<string> strings;
vector<double> doubles;

ifstream infile("filename.txt"); //open your file

while(infile >> discard >> strInput >> dblInput) {
  //now discard stores the value 1, which you don't use;
  //strInput stores Gt or other 1-3 character long string;
  //dblInput stores the double

 //operations to store the values that are now in strInput and dblInput
 //for example, to push the values into a vector:
   strings.push_back(strInput);
   doubles.push_back(dblInput);

}

infile.close();