【问题标题】:Convert string from getline into a number将字符串从 getline 转换为数字
【发布时间】:2014-06-02 07:40:27
【问题描述】:

我正在尝试用向量创建一个二维数组。我有一个文件,每行都有一组数字。所以我做了什么我实现了一个拆分函数,每次我有一个新数字(由\t分隔)时,它都会拆分它并将其添加到向量中

vector<double> &split(const string &s, char delim, vector<double> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        cout << item << endl;
        double number = atof(item.c_str());
        cout << number;
        elems.push_back(number);
    }
    return elems;
}


vector<double> split(const string &s, char delim) {
    vector<double> elems;
    split(s, delim, elems);
    return elems;
}

之后我只是简单地遍历它。

int main()
{
    ifstream file("./data/file.txt");
    string row;
    vector< vector<double> > matrix;

    int line_count = -1;
    while (getline(file, row)) {
        line_count++;
        if (line_count <= 4) continue;
        vector<double> cols = split(row, '\t');
        matrix.push_back(cols);
    }
...
}

现在我的问题就在这里:

   while (getline(ss, item, delim)) {
        cout << item << endl;
        double number = atof(item.c_str());
        cout << number;

其中 item.c_str() 被转换为 0。那不应该仍然是一个与 item 具有相同值的字符串吗?如果我直接从字符串到 c_string,它适用于一个单独的示例,但是当我使用这个 getline 时,我最终会遇到这种错误情况,

提示?

【问题讨论】:

  • 出错时item的值是多少? (您可以使用 C++ 版本 std::stod 而不是 atof - 如果输入不是有效的 double 值,则会引发异常。
  • 用 std::stod 我得到libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stod: no conversion Abort trap: 6
  • 如果您收到来自stod 的错误,这意味着您的输入格式不正确,就像那里可能有一个额外的选项卡一样。在下面的答案中使用stringstream 可以避免这个问题,因为它会跳过额外的空白。如果您仍然遇到问题,那么输入失败的示例会很有帮助。
  • 问题是我卡在第一行的第一个数字(恰好是“1”)
  • 没有看到您的输入,很难猜出问题所在。这有效:demo 这基本上是您的主要功能,具有类似于以下答案中发布的拆分功能。唯一的区别是来自cin 而不是文件的输入。

标签: c++


【解决方案1】:

使用字符串流代替 atof

while(!ss.eof())
{
    double number;
    ss>>number;
}

编辑: 我已经更新了你的 split 函数,去掉了多余的 return。

void split(const string &s, vector<double> &elems) {
    stringstream ss(s);
    while (!ss.eof()) {
        double number;
        ss >> number;
        cout << number;
        elems.push_back(number);
    }

}

int main()
{
    std::vector<double> columns;
    split("1.32\t1.65\t1.98456\t2.34",columns);
    return 0;
}

【讨论】:

  • 你能把它放在上下文中吗? ss有多个数字不是一个ss怎么去下一个ss?
  • 我已经添加了我的使用方式,您可能需要检查拆分行时得到的内容。
  • 非常感谢,但是我的问题是关于向量中的向量(或二维数组),我设法得到行而不是列
猜你喜欢
  • 2015-07-19
  • 2022-08-22
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 1970-01-01
相关资源
最近更新 更多