gpt4 book ai didi

c++ - C++如何读取特定的第一个字符并保存数据

转载 作者:行者123 更新时间:2023-11-28 02:56:21 27 4
gpt4 key购买 nike

我是C++新手。

我想写一个可以读取文件的程序,如下所示:

p   6   9
n 3
b 1 6.0
b 1 4.0
b 2 2.0

在这样的文件中,我想读取第一个字符 b 的行。
我尝试使用getline() 来判断第一个字符是否为b。
然而,我面临的问题是我可以很容易地保存第一个 int,但我不能保存第二个 double 数。我知道原因是我把它保存在 char 中,所以双数是分开的(比如 6.0 变成 '6' '.' '0')
那么,是否有其他方式来保存整数和 double 的行?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){

char b[100];
string word;
int a,d;
double c;
ifstream infile("test.txt");
while(infile){
infile.getline(b,100);
if(b[0] == 'b'){
//where I don't know how to save the data
}
}
}

很抱歉我生疏的英语,但真的需要你的帮助。

最佳答案

只需将整个字符串放入 std::istringstream并使用 >>> 获取其数据:

int int_value;      // second data will be saved here, e.g. 1
float float_value; // third data will be saved here, e.g. 6.0

char char_dummy; // dummy char to hold the first char, e.g. 'b'
istringstream iss(b);
iss >> char_dummy >> int_value >> float_value;

关于c++ - C++如何读取特定的第一个字符并保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21888164/

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