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

How to read specific first character and save the data by C++

本文关键字:字符 第一个 C++ 数据 保存 何读取 读取      更新时间:2023-10-16

我是C++的新手。

我想编写一个程序,可以读取以下文件:

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

在这样的文件中,我想读取带有第一个字符b的行。
我尝试使用getline()并判断第一个字符是否为 b。
但是,我面临的问题是我可以轻松保存第一个整数,但第二个双精度数我无法保存它。我知道原因是我将其保存在字符中,因此 dobule 编号(such like 6.0 become '6' '.' '0')分开。
因此,它有没有其他方法可以保存带有整数和双精度的行?

#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;