我想读取 C++ 中的输入文件,其结构(或缺乏)将类似于一系列带有以下内容的行:文字=数字, 例如
input1 = 10
input2 = 4
set1 = 1.2
set2 = 1.e3
我想把这个号码从队列中取出,然后把剩下的扔掉。数字可以是整数或双精度数,但我知道它们什么时候是一个或另一个。
我也想读一下,例如
input1 = 10
input2=4
set1 =1.2
set2= 1.e3
从而对用户来说更加鲁棒。我认为这意味着它不应该以格式化的方式显示为红色。
无论如何,有一个聪明的方法可以做到这一点吗?
我已经尝试过以下操作,但对我所做的事情知之甚少,所以结果如预期......没有成功。
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <boost/lexical_cast.hpp>
#include <string>
using namespace std;
using namespace boost;
int main(){
string tmp;
char temp[100];
int i,j,k;
ifstream InFile("input.dat");
//strtol
InFile.getline(temp,100);
k=strtol(temp,0,10);
cout << k << endl;
//lexical_cast
InFile.getline(temp,100);
j = lexical_cast<int>(temp);
cout << j << endl;
//Direct read
InFile >> tmp >> i;
cout << i << endl;
return 0;
}
只需一次阅读一行。
然后用“=”符号分割每一行。使用流功能完成剩下的工作。
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::ifstream data("input.dat");
std::string line;
while(std::getline(data,line))
{
std::stringstream str(line);
std::string text;
std::getline(str,text,'=');
double value;
str >> value;
}
}
通过错误检查:
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::ifstream data("input.dat");
std::string line;
while(std::getline(data,line))
{
std::stringstream str(line);
std::string text;
double value;
if ((std::getline(str,text,'=')) && (str >> value))
{
// Happy Days..
// Do processing.
continue; // To start next iteration of loop.
}
// If we get here. An error occurred.
// By doing nothing the line will be ignored.
// Maybe just log an error.
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)