我看到了一些我无法理解的东西。
#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
时返回的字符串,并且能够打印当前行。
下面是一些在当前行中查找逗号的代码
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);
注:这段代码假设输入中有逗号,如果没有,它很可能会崩溃。 你应该经常检查你的输入数据。
你把你的数字解析错了。 字符串是字符的序列。 为了从字符串中解析一个数字,您必须执行以下操作
std::stoi(current_line.substr(0, current.find(',')));
(假设存在','
。在生产代码中,您可能需要在那里进行错误检查)
您正在使用的代码
std::string(std::begin(current_line), std::begin(current_line) + sizeof(long));
创建一个由4个字符组成的临时字符串,因为sizeof(long)
通常是4个字节。
你只需要:
long value = std::stol(current_line);
std::stol
跳过前导空格,然后将剩余文本解析为整数值。 当它碰到一个不能是整数一部分的字符时,它就会停止。 因此当它到达,
时将停止。