C++ 如何使用逗号分隔值读写文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1474790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read-write into/from text file with comma separated values
提问by Curious
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.
我也有整数向量来存储数据。所以,我想读取第一行,然后计算该行中元素的总数,这里是 5 (1,2,3,4,5) 并将它们存储在数组/向量中,然后读取下一行并将它们存储在向量中一次又一次,直到我达到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
谢谢
回答by Martin York
Step 1: Don't do this:
第 1 步:不要这样做:
while(!file.eof())
{
getline(file,line);
numlines++;
}
numline--;
The EOF is not true until you try and read past it. The standard pattern is:
在您尝试阅读它之前,EOF 是不正确的。标准模式是:
while(getline(file,line))
{
++numline;
}
Also note that std::getline()
can optionally take a third parameter. This is the character to break on. By default this is the line terminator but you can specify a comma.
另请注意,std::getline()
可以选择采用第三个参数。这是要突破的角色。默认情况下,这是行终止符,但您可以指定逗号。
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 something 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));
}
回答by amrita Jaiswal
here I m posting the code for CSV read as well as write code. I have checked its working fine.
在这里,我发布了 CSV 读取和写入代码的代码。我已经检查过它的工作正常。
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
void readCSV(istream &input, vector< vector<string> > &output)
{
string csvLine;
// read every line from the stream
while( getline(input, csvLine) )
{
istringstream csvStream(csvLine);
vector<string> csvColumn;
string csvElement;
// read every element from the line that is seperated by commas
// and put it into the vector or strings
while( getline(csvStream, csvElement, ',') )
{
csvColumn.push_back(csvElement);
}
output.push_back(csvColumn);
}
}
int main()
{
ofstream myfile;
string a;
fstream file("b.csv", ios::in);
myfile.open ("ab.csv");
if(!file.is_open())
{
cout << "File not found!\n";
return 1;
}
// typedef to save typing for the following object
typedef vector< vector<string> > csvVector;
csvVector csvData;
readCSV(file, csvData);
// print out read data to prove reading worked
for(csvVector::iterator i = csvData.begin(); i != csvData.end(); ++i)
{
for(vector<string>::iterator j = i->begin(); j != i->end(); ++j)
{
a=*j;
cout << a << " ";
myfile <<a<<",";
}
myfile <<"\n";
cout << "\n";
}
myfile.close();
system("pause");
}
回答by hock
Try the stringstreamclass:
试试stringstream类:
#include <sstream>
Just in case, look up Stroustrup's "The C++ Programming Language Special Edition" page 641 example.
以防万一,请查阅 Stroustrup 的“The C++ Programming Language Special Edition”第 641 页示例。
It works for me and I had a hell of a time trying to figure this one out.
它对我有用,我花了很长时间试图解决这个问题。