首页 > 解决方案 > 究竟如何解释 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预定义类型。

标签: c++stdifstream

解决方案


这是一些在当前行中查找逗号的代码

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

请注意,此代码假定输入中有逗号,如果没有,它可能会崩溃。您应该始终检查您的输入数据。


推荐阅读