我无法读取30行的内容.csv文件后,进入下面的结构一个结构:无法读取.csv文件到一个类,它表示一个矢量
class Entry {
public:
std::string GID;
std::string DName;
std::string Phone;
std::string POC;
std::string Item;
std::string Category;
double amount;
};
我希望能够创建一个可以读取名为“Donations.csv”的csv文件的函数,并删除逗号,因为我想创建一个可能类似于如下的向量:std::vector<Entry> entries;
,这样我就可以根据向量中的任何元素对多个项目进行排序。因此,例如说我想通过DNAME排序,代码会是这个样子:
// sort by DName
std::sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b) {
return a.DName.compare(b.DName) < 0;
});
我被告知不要使用多个载体,因为这并不安全,但有效的,如果它可以帮助别人,这是如何读取一个CSV文件分成多个向量:
公平的警告,采用EOF控制器是错误的,REFER HERE
虽然,这个代码将工作刚刚好,我亲自测试了 - 上的.csv无数次文件。
int main()
{
ifstream inFile; // Input file handler
ofstream outFile; // Output file handler
vector<string> GID; // Vector holding Gift ID
vector<string> DName; // Vector holding Donor Name
vector<string> Phone; // Vector holding Phone Number
vector<string> POC; // Vector holding point of contact
vector<string> Item; // Vector holding item donated
vector<string> Category; // Vector holding type of item donated
vector<double> amount; // Vector holding amount of donated items
int Input; // User selection choice from menu
// opening data file
inFile.open("Donations.csv");
if (!inFile) // If statement to check for file erroe
{
cout << "Input file did not open. Program will exit." << endl; // Does not compute!
exit(0);
}
// reading contents
string str; // temp string to hold parse comma
double temp; // temp double to hold null spaces for atoi function/strtod
getline(inFile, str, ','); // read first GID string outside of loop so that we
// won't accidentally reach the end of the file in the MIDDLE of the loop
while (!inFile.eof()) // end of file not reached
{
GID.push_back(str);
getline(inFile, str, ','); // get the contents of the line until a comma is encountered and push it into the necessary vector
DName.push_back(str);
getline(inFile, str, ',');
Phone.push_back(str);
getline(inFile, str, ',');
POC.push_back(str);
getline(inFile, str, ',');
Item.push_back(str);
getline(inFile, str, ',');
Category.push_back(str);
getline(inFile, str, '\n'); // get until the end of the line but split for parsing
// convert string to double using strtod and c_str
temp = strtod(str.c_str(), NULL);
// now push double onto vector
amount.push_back(temp);
getline(inFile, str, ','); // read in GID here instead of the top. If we are at the end
// of the file, it won't work and end-of-file flag will be set which is what we want.
}
inFile.close();
}
“我有麻烦”是不是一个有用的问题说明。从代码的偶然检查中,有几个显而易见的问题 - 来自'while(!inFile.eof())'是一个明显的bug(请参阅http://stackoverflow.com/questions/5431941/why-is- while-feof-file-always-wrong)到使用'getline()'的脆弱,容易出错的解析 - 但没有一个特定的问题,没有具体的答案是可能的。 –
@SamVarshavchik谢谢先生,我已经重述了这个问题。谢谢'while(!inFile.eof())'的提醒。我会更新这篇文章以反映这一点。 –
@SamVarshavchik我只是想知道如何读取一个csv文件到一个结构,并从输入文件中删除逗号 –