如何使用逗号分隔值对文本文件进行读写 [英] How to read-write into/from text file with comma separated values

查看:526
本文介绍了如何使用逗号分隔值对文本文件进行读写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的文件类似于逗号分隔值,则如何从文件中读取数据

  1,2,3 ,4,5 \\\

6,7,8,9,10 \\\

\\\

并且在读取文件后,我想将数据写回其他文件,如同上面的格式。



,使用

 字符串; 
while(!file.eof()){
getline(file,line);
numlines ++;
}
numline--; //删除最后一个空行

但是如何知道行/行中的总位数?



我也有ints的向量来存储数据。
所以,我想读取第一行,然后计数该行中的元素总数,这里是5(1,2,3,4,5)并将它们存储在数组/向量中,并读取下一行和将它们重新存储在向量中等等,直到我到达EOF。



然后,我想把数据写入文件,我想这将做写作数据到文件,

  numOfCols = 1; 
for(int i = 0; i {
file< vector.at(i);
if((numOfCols< 5)file<<,; // print comma(,)
if((i + 1)%5 == 0)
{
file<< endl; //在第5个值后打印换行
numOfCols = 1; //从第1行开始,用于下一行
}
numOfCols ++;
}
文件<< endl; //上一个新行

我的主要问题是如何从文件读取数据用逗号分隔的值



感谢

解决方案

步骤1:
不要这样做:

  while(!file.eof ))
{
getline(file,line);
numlines ++;
}
numline--;
pre>

在尝试读取之前,EOF是不正确的。

标准模式是:

  while(getline(file,line))
{
++ numline;
}

还要注意,std :: getline()可以选择第三个参数,这是打破的字符。默认情况下这是行终止符,但您可以指定逗号。

  while(getline(file,line))
{
std :: stringstream linestream(line);
std :: string value;

while(getline(linestream,value,','))
{
std :: cout< Value(<< value<<)\\\
;
}
std :: cout<< Line Finished<< std :: endl;

}

如果将所有值存储在一个向量中,它们使用固定宽度。然后我会这样做。

  struct LineWriter 
{
LineWriter(std :: ostream& str,int size)
:m_str(str)
,m_size(size)
,m_current(0)
{}

// std :: copy()赋值给迭代器。
//看起来像这样(* result)=< value> ;;
//因此覆盖运算符*和运算符= to
LineWriter&运算符*(){return * this;}
void operator =(int val)
{
++ m_current;
m_str<< val<< (((m_current%m_size)== 0)?\\\
:,);
}

// std :: copy()递增迭代器。但是这不是usfull这里
//所以只是实现太空的方法来处理增量。
void operator ++(){}
void operator ++(int){}

//本地数据。
std :: ostream& m_str;
int const m_size;
int m_current;
};

void printCommaSepFixedSizeLinesFromVector(std :: vector const& data,int linesize)
{
std :: copy(data.begin(),data.end(),LineWriter std :: cout,linesize));
}


How do I read data from a file if my file is like this with comma separated values

1, 2, 3, 4, 5\n
6, 7, 8, 9, 10\n
\n

and after reading the file, I want to write the data back into other file as same format above.

I can get total number of lines, using

string line;
while(!file.eof()){
      getline(file,line);
      numlines++;
    }
    numline--; // remove the last empty line

but how can I know total number of digits in a row/line ??

I also have vector of ints to store the data. So, I want to read the first line and then count total number of elements in that line, here 5 (1,2,3,4,5) and store them in array/vector, and read next line and store them in vector again and so on till I reach EOF.

Then, I want to write the data to file, again, I guess this will do the job of writing data to file,

numOfCols=1;
for(int i = 0; i < vector.size(); i++)
{
    file << vector.at(i);
    if((numOfCols<5) file << ",";//print comma (,)
    if((i+1)%5==0)
    {
                  file << endl;//print newline after 5th value
                  numOfCols=1;//start from column 1 again, for the next line
    }
    numOfCols++;
}
file << endl;// last new line

So, my main problem is how to read the data from file with comma separated values ??

Thanks

解决方案

Step 1: Dont do this:

while(!file.eof())
{
    getline(file,line);
    numlines++;
}
numline--;

The EOF is not true until you try and read past it.
The standard pattern is:

while(getline(file,line))
{
    ++numline;
}

Also note that std::getline() can optinally take a third parameter. This is the character to break on. By default this is the line terminator but you can specify a comma.

while(getline(file,line))
{
    std::stringstream   linestream(line);
    std::string         value;

    while(getline(linestream,value,','))
    {
        std::cout << "Value(" << value << ")\n";
    }
    std::cout << "Line Finished" << std::endl;

}

If you store all the values in a single vector then print them out using a fixed width. Then I would do somthing like this.

struct LineWriter
{
        LineWriter(std::ostream& str,int size)
                :m_str(str)
                ,m_size(size)
                ,m_current(0)
        {}

        // The std::copy() does assignement to an iterator.
        // This looks like this  (*result) = <value>;
        // So overide the operator * and the operator = to
        LineWriter& operator*() {return *this;}   
        void operator=(int val)
        {
                ++m_current;
                m_str << val << (((m_current % m_size) == 0)?"\n":",");
        }

        // std::copy() increments the iterator. But this is not usfull here
        // so just implement too empty methods to handle the increment.
        void operator++()       {}
        void operator++(int)    {}

        // Local data.
        std::ostream&           m_str;
        int const               m_size;
        int                     m_current;
};

void printCommaSepFixedSizeLinesFromVector(std::vector const& data,int linesize)
{
    std::copy(data.begin(),data.end(),LineWriter(std::cout,linesize));
}

这篇关于如何使用逗号分隔值对文本文件进行读写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆