繁体   English   中英

Getline从txt文件读取数据

[英]Getline to read data from txt file

使用getline命令从简单的.txt文件提取数据时,我遇到了一些问题。

txt文件非常简单:一列400个数字。 我使用向量将它们存储为以下代码:

int i = 0;
string line;
vector <double> vec;

while (getline(input, line))
{
    vec.push_back(i);
    N++;
    input >> vec[i];
    i++;
} 

它正确地创建了一个包含400个元素的向量,但是txt文件的第一行被忽略了(我以vec [0] = txt文件的第二行而不是第一行结束),而第399个元素是399,而不是txt文件的第400行。

我尝试了其他几种方法来提取此数据,但未成功。

谢谢您的帮助!

编辑:

我已经根据一些评论编辑了代码:

vector <double> vec;
string line;
double num;

while (getline(input, line))
{
    input >> num;
    vec.push_back(num);
}

不幸的是,它仍然跳过了我的文本文件的第一行。

编辑2->解决方案:

感谢您的所有评论,我意识到同时使用getline和input >> num时我做错了什么;

解决问题的方法如下:

double num;
vector <double> vec;

while (input >> num)
{
    vec.push_back(num);
}

您只需将std::istream_iterator传递给std::vector构造函数即可,无需循环即可将整个文件读入向量:

std::vector<int> v{
    std::istream_iterator<int>{input}, 
    std::istream_iterator<int>{}
};

例如:

#include <iostream>
#include <iterator>
#include <vector>
#include <exception>

template<class T>
std::vector<T> parse_words_into_vector(std::istream& s) {
    std::vector<T> result{
        std::istream_iterator<T>{s},
        std::istream_iterator<T>{}
    };
    if(!s.eof())
        throw std::runtime_error("Failed to parse the entire file.");
    return result;
}

int main() {
    auto v = parse_words_into_vector<int>(std::cin);
    std::cout << v.size() << '\n';
}

由于再次读取文件,因此您松散了第一行-此处:

while (getline(input, line))
    // ^^^^^^^ Here you read the first line
{
    input >> num;
 // ^^^^^^^^ Here you will read the second line

您告诉过您想要双打的向量-例如:

std::vector<double> vec;

因此,您应该使用std::stodgetline读取的行转换为double。 喜欢:

while (std::getline(input, line))
{
    // Convert the text line (i.e. string) to a floating point number (i.e. double)
    double tmp;
    try
    {
        tmp = stod(line);
    }
    catch(std::invalid_argument)
    {
        // Illegal input
        break;
    }
    catch(std::out_of_range)
    {
        // Illegal input
        break;
    }

    vec.push_back(tmp);
} 

不要 input >> num; 在循环内。

如果您真的想使用input >> num; 那么您将不能使用getline 也就是说-您可以使用任何一个,但不能同时使用。

如下更改您的while循环:

while (getline(input, line))
{
    vec.push_back(line);
    //N++;
    //input >> vec[i];
    //i++;
} 

也可以尝试以下选项

 do{
    vec.push_back(i);
    //N++;
    //i++;
 }while (input >> vec[i++]);

首先在第一次迭代中将vector放入0:

vec.push_back(i);

然后,在读取第一行之后,您将读取下一个字符串,但是从文件中获取流的指针已经在不同的位置,因此您覆盖此0并从流中跳过第一个值。 更糟糕的是,它奇怪地转换为两倍:

input >> vec[i];

这样,您会出错。 尝试这个:

while (std::getline(file, line)) {
    //In c++11
    vec.emplace_back(std::stod(line));
    //In c++ 98, #include <stdlib.h> needed
    //vec.push_back(atof(line.c_str())); 
}

这假设您将始终拥有正确的文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM