C ++如何读取txt文件并检索除字符串之外的数值(反之亦然)

时间:2015-05-10 14:38:10

标签: c++ fstream ifstream

我一直在教自己C ++,并在寻找如何做到这一点。让我举一个例子来澄清我的意图。

这是一个txt文件,内容如下。

Matt   18  180.0   88.5
Angela 20  155.5   42.2

每行都有关于某人姓名,年龄,身高和体重的信息。

我一直试图做的是分别获取这4种类型的信息,并根据信息类型将它们存储在不同的变量中。

vector<string> name; //"Matt" or "Angela" are stored here.
vector<int> age; //18 or 20
vector<double> height; //The same logic goes for this vector and the next one
vector<double> weight;

至少我发现使用ifstreamObject.open(filename.c_str())getline(ifstreamObject, string)可以将txt文件中的信息存储在字符串变量中。但是,通过使用此方法,我只获得与每行对应的字符串值。换句话说,我无法区分字符串值和数值。

有可能没有任何其他方法可以从txt文件中获取信息。尽管如此,为了以防万一,我想在此之前就如何以这种方式获取信息提出一些建议,然后再放弃。

任何建议都将受到赞赏。

3 个答案:

答案 0 :(得分:3)

您可以做的是直接使用流

std::string name;
int age;
double height, weight;

while(ifstreamObject >> name >> age >> height >> weight)
{
    // process name, age, height and weight
}

缺点是流插入操作符将读取直到第一个空格。因此,如果您想将整行读作字符串,请使用getline,相应地处理字符串,&#34; map&#34;将getline读取的字符串返回到istringstream

std::istringstream is(str); // constructs an istringstream from the string str

然后使用is与您使用流的方式类似。

答案 1 :(得分:0)

如果您知道每个条目之间存在某个字符(如选项卡),您可以使用String.find_first_of和子字符串将字符串分成几部分并将它们解析为您拥有的字段。 查看http://www.cplusplus.com/reference/string/string/了解详情

答案 2 :(得分:0)

您可以使用stl :: string方法操作行字符串以分别提取这4种类型的信息。

使用std::string::find_first_of查找空白的每个开头,并使用std::string::find_first_not_of查找每个非空白字符。使用std::string::substr从行字符串中提取子字符串。还可以使用atoi将字符串值转换为int。

例如,

//rowSrting holds the data of one line in file

std::size_t nameEnd = rowString.find_first_of(" ");
string name = rowString.substr(0, nameEnd-1);

std::size_t ageFirst = rowString.find_first_not_of(" ", nameEnd);
std::size_t ageEnd = rowString.find_first_of(" ", ageFirst );
int age = atoi(rowString.substr(ageFirst, ageEnd-1));