如何读取特定的第一个字符并按C++保存数据
How to read specific first character and save the data by C++
我是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;
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- C++:使用另一个字符将一个字符大写
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 为什么第一个Dynamic_cast没有投射到基类?
- 将第一个n个字符复制到std :: string
- 一个奇怪的字符出现在我的字符数组的第一个
- 当一长串字符传递给第一个 cin 时,为什么不暂停第二个 cin 上的输入?
- 哪个字符是 c++ 中 4 个字符中的第一个
- 从 std::string 中提取(第一个)UTF-8 字符