Getline从txt文件中读取数据

时间:2018-05-22 15:37:22

标签: c++ getline istream

我使用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文件的第2行而不是第1行)而第399个元素是399而不是第400行的txt文件。

我尝试了其他几种方法来提取这些数据但却没有成功。

感谢您的帮助!

修改

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

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

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

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

编辑2 - &gt;解决方案:

感谢您的所有评论,我意识到在使用getline和输入&gt;&gt;时我做错了什么。 NUM;

以下是问题的解决方法:

double num;
vector <double> vec;

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

4 个答案:

答案 0 :(得分:2)

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

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

E.g:

#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';
}

答案 1 :(得分:1)

由于再次从文件中读取,你松开了第一行 - 这里:

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。也就是说 - 你可以使用而不是两者。

答案 2 :(得分:0)

更改你的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++]);

答案 3 :(得分:0)

首先在第一次迭代中将0放在向量中开始:

vec.push_back(i);

然后在你读完第一行之后你读了下一个字符串,但是来自文件的流get指针已经在不同的地方,所以你重写这个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())); 
}

这假设您将始终拥有适当的文件。

相关问题