首页 文章

stringstream >>不一致的'\n'分隔符行为

提问于
浏览
3

我有以下函数来读取文本流并将其切割为给定类型的向量:

template<class Type>
void parse_string(std::vector<Type> &type_vector, char *string) 
{
    std::stringstream stream(string);
    while (stream.good()) 
    {
        Type t;
        stream >> t;
        type_vector.push_back(t);
    }
}

char *string 参数是一个文本块,表示浮点数或字符串,每个字符串用 ' ''\n' 分隔 .

现在我的问题是,当给定 std::vector<float> type_vector 时, parse_string 函数将由 ' ''\n' 分隔符分隔 . 例如:

0.01 0.02 0.03 0.04
0.05 0.06 0.07 0.08

它将 '0.04''0.05' 作为单独的标记读取 . 这就是我要的!

但是,如果给定 std::vector<std::string> type_vectorparse_string 将仅由 ' ' 分隔 . 因此,如果我的文本如下:

root_joint left_hip left_knee left_ankle
left_foot right_hip right_knee right_ankle

它会将'left_ankleleft_foot'读作单个标记 . 它似乎没有考虑到 'left_ankle''left_foot' 之间存在 '\n' .

是什么造成的?

编辑:

调试器中显示的确切char *参数如下:

0.01 0.02 0.03 0.040.05 0.06 0.07 0.08

root_joint left_hip left_knee left_ankleleft_foot right_hip right_knee right_ankle

所以它似乎完全忽略了文件中的'\ n'...

EDIT2:

好吧,我弄清楚我做错了什么 . 正如你们许多人所指出的那样,它与stringstream无关 .

我的解析器需要文件的std :: vector副本 . 在将文件读入字符串并将其转换为向量的过程中,我使用了getLine(std :: ifstream,std :: string)函数,正如您所猜测的那样,剥离'\ n'换行符 .

1 回答

  • 1

    您正在错误地读取字符串,因此\ n被丢弃 . \ n应导致分裂 .

相关问题