c++ - 究竟如何解释 C++ 中 std::getline(stream, string) 函数填充的字符串
问题描述
我看到了一些我无法理解的东西。
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream someStream;
someStream.open("testfile");
std::string current_line;
if ( someStream.good() )
{
while (std::getline(someStream, current_line))
{
std::cout << current_line << "\n";
std::cout << std::string(std::begin(current_line), std::begin(current_line) + sizeof(long));
std::cout << "\n";
}
}
return 0;
}
当前testfile
目录中的 有格式。
319528800,string1
319528801,string2
319528801,string3
319528802,string4
我要解决的问题:
我想在每行的第一个逗号之前提取数字,然后使用每个数字作为键来制作地图。我知道这些数字是重复的。但是我无法制作地图,它一直只插入第一个数字。
上面的代码想要打印出每行第一个逗号之前的数字。但它不能这样做。但是,我正在尝试打印每次正确调用时返回的字符串,std::getline
并且我能够打印当前行。
编辑:我过于愚蠢。我确实忽略了这一点,sizeof
或者std::size
始终是const
预定义类型。
解决方案
这是一些在当前行中查找逗号的代码
while (std::getline(someStream, current_line))
{
std::cout << current_line << "\n";
// get position of comma
size_t pos = current_line.find(',');
// get string before comma
std::string tmp = current_line.substr(0, pos);
// convert to long
long num = stol(tmp);
请注意,此代码假定输入中有逗号,如果没有,它可能会崩溃。您应该始终检查您的输入数据。
推荐阅读
- r - R:存储要由函数返回的变量内容,如果重新分配对象,则该函数不会更改
- selenium - selenium.common.exceptions.NoSuchElementException:消息:无法找到元素 [id=""]
- conda - The Littlest JupyterHub:使用多通道在 Hyper-V 上安装错误
- linux - 如何获得外壳提示?
- spring-boot - 为什么我们需要使用spring data jpa而不是附加到实体生命周期事件的回调方法
- java - new Arraylist<>(subset) 是如何工作的?它会创建一个新的数组列表并将子集的元素复制到其中吗?
- android - 为什么我的 webview 应用程序在我在 avd android 5 lolipop 上运行时崩溃,但相同的应用程序在我的 android 手机上运行良好,带有 android 11
- node.js - 由于 React 应用程序中的内容安全策略,图像未加载
- java - java 8 LocalTime 到 LocalTime UTC
- python - 如何将 keras 张量转换为 numpy 数组