gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:39:07 25 4
gpt4 key购买 nike

我一直在自学 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 文件中获取信息。尽管如此,为了以防万一,在我放弃之前,我想在这里询问一些关于如何以这种方式获取信息的建议。

如有任何建议,我们将不胜感激。

最佳答案

你可以做的是直接使用流,

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

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

缺点是流插入运算符将读取到第一个空白。因此,如果您想将整行作为字符串读取,则使用 getline,相应地处理字符串,将 getline 读取的字符串“映射”回 >字符串流,

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

然后像使用流一样使用 is

关于C++如何读取txt文件并检索数值,除了字符串(反之亦然),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com