不理解为什么文本文件内容没有存储在向量的各个元素中

时间:2012-08-17 21:53:46

标签: c++

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    ifstream inFile("test.txt");
    string line;

    while(getline(inFile, line))
    {
        istringstream meh(line);
        int n;
        vector<int> v;

        while(meh >> n)
            v.push_back(n);
    }
}

我的test.txt文件如下:

429384
392041
230138
099938
243324

如果我尝试打印v [0],我会得到整个数字序列(42938 ... 3324),而不仅仅是第一个数字4.有人可以解释为什么会发生这种情况吗?

2 个答案:

答案 0 :(得分:1)

如果我理解正确并且你真的想要遍历每一行中的每个数字,那么你可以试试这个:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main()
{   
    ifstream inFile("test.txt");
    string line;

    while(getline(inFile, line))
    {   
        vector<int> v;
        int n;
        // loop through the string
        for(int i = 0; i < line.length(); i++) {
           // check whether the byte is numeric
           if(line[i] >= '0' && line[i] <= '9') {
               // convert it to a real integer
               int n = line[i] - '0';
               v.push_back(n); // add it to the vector
           }   
        }   

        // just to show they have been added
        int j;
        for (vector<int>::size_type j = 0; j < v.size(); ++j) {   
            std::cout << v[j] << std::endl;
        }   
    }   
}

向量 v 只有循环的范围,所以文件的每一行都有自己的向量;然而,这可能是你想要的,而不知道我不能再说的实际应用了。

答案 1 :(得分:1)

输出数据时可能会出错。您的代码实际上只存储了一个int - 每行的值 - 整行存储在v [0]中。然后你在流中写了整数,忘记在while循环开始处理下一行之前写一个新行。因此,您的输出是一个大数字。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    istringstream inFile("text.txt");
    string line;
    vector<vector<int> > vector_container;

    while(getline(inFile, line))
    {
        istringstream meh(line);
        char n;
        vector<int> v;

        while(meh >> n)
            v.push_back(static_cast<int>(n)-48);

        vector_container.push_back(v);
    }
    // this would output your numbers the way they were
    // stored inside your file
    for(int i = 0; i < vector_container.size(); ++i){
        for(int j = 0; j < vector_container[i].size(); ++j){
             cout << vector_container[i][j];
        }
        cout << endl;
    }

}

这应该按照你预期的方式工作。您将在vector<int>内有一个vector<vector<int> >容器。第一个将您的号码存储在一行中,而每个字符将单独存储。后一个向量只是存储行数的向量。当您查看ASCII表时,charint转换应该自行解释。