C++从文件中读取不同类型的数据,直到有一个以数字开头的字符串
C++ read different kind of datas from file until there's a string beginning with a number
在C++中,我想从包含不同类型数据的输入文件中读取:首先是参赛者的名字(2 个或更多带有空格的字符串(,然后是 ID(没有空格的字符串,总是以数字开头(,然后是另一个没有 ws 和数字的字符串(运动及其实现的位置(。
例如:
我Josh Michael Allen 1063Szinyei running 3 swimming 1 jumping 1
向你展示我开始写的代码,然后卡住了。
void ContestEnor::next()
{
string line;
getline(_f , line);
if( !(_end = _f.fail()) ){
istringstream is(line);
is >> _cur.contestant >> _cur.id; // here I don't know how to go on
_cur.counter = 0;
//...
}
}
提前感谢您的帮助。
您应该考虑将std::getline
与分隔符一起使用。这样,您可以在空格字符上分隔并读取,直到找到数字中第一个字符的字符串。这是一个简短的代码示例(这看起来很像家庭作业,所以我不想为你写太多;):
std::string temp, id;
while (std::getline(_f, temp, ' ')) {
if (temp[0] >= 0 && temp[0] <= '9') {
id = temp;
}
// you would need to add more code for the rest of the data on that line
}
/* close the file, etc. */
这段代码应该是不言自明的。要知道的最重要的事情是,您可以使用std::getline
来获取数据,直到分隔符。使用分隔符,就像在换行符上分隔的默认行为一样。因此,名称getline
并不完全准确 - 如果需要,您仍然可以只获取一行的一部分。
相关文章:
- 是否可以定义一个以向量<T>作为值的unordered_map?
- 如何初始化一个标准::字符串数组?
- readAll() 或 readAllStandardOutput() 在执行之前也返回一个空字符串
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 我是 C++ 的新手,我试图调用 make 一个以 2 个类作为其参数的类构造函数
- 我怎么能有一个以2D数组为参数的函数,而数组有一个我想更改的参数/维度
- 实现一个函数,该函数将字符串作为输入并返回一个新字符串,辅音字母不替换为 "!"
- 从C++代码中以字符串形式运行多行 bash 脚本
- 为什么glGetProgramInfoLog返回一个空字符串?
- 当字符串中只有一个"GOOD"字符串可用时,从没有空格的字符串中提取第一个单词的最佳和有效方法?
- 如何在yaml-cpp中写一个版本字符串作为文字(不是字符串)
- 以字符串向量作为值的哈希映射
- llvm 调用一个以 char * 作为参数的外部函数
- 我不知道如何创建一个以数字/字母顺序打印出我的整数或字符串的程序
- C++从文件中读取不同类型的数据,直到有一个以数字开头的字符串
- std::string::c_str() 是否总是返回一个以 null 结尾的字符串
- 如何生成一个以非null结尾的c字符串
- 多维数组-如何在c++中将两个令牌设置为一个以波浪线分隔的字符串
- 通过ZeroMQ以字符串形式接收对象,然后通过另一个套接字以零拷贝发送对象的正确方法是什么