这是我从.csv文件中获取的代码,它在beetween到分隔符之间得到了痒,并给出了那些分隔符的位置。但是这确实只使第一行如何继续第二行例如?
#include <tchar.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
//#include <limits>
using namespace std;
#define TAILLE_MAX_LIGNE 1203
int _tmain(int argc, _TCHAR* argv[])
{
char stringFile [TAILLE_MAX_LIGNE];
string stringLineToAnalyse;
size_t positionCharOld, positionCharNew;
string separateurChar = ";";
string contenuLocalChamp = "";
vector <string> localStringVector;
localStringVector.clear(); // Initialisation du vecteur // VECTOR INTIALISE
ifstream file;
file.open("C:/Users/Alex/Desktop/STAGE/test.csv");
if(file.is_open())
{
file.getline(stringFile, TAILLE_MAX_LIGNE);
// file.ignore(numeric_limits<streamsize>max(),'\n'));
stringLineToAnalyse = stringFile;
cout << "tout va bien" << endl;
cout << stringLineToAnalyse << endl;
// initialisation de la recherche dans la ligne
// INITIALISE SEARCH INTO THE LIGNE
positionCharOld = 0;
bool finDelaBoucle = false;
while(finDelaBoucle == false)
{
// boucle itérative
positionCharNew = stringLineToAnalyse.find(separateurChar, positionCharOld);
if(positionCharNew != string::npos)
{
cout << "separateur trouve a la position " << positionCharNew << endl; // SEPARATOR POSITION
if((positionCharNew-positionCharOld) > 0)
{
contenuLocalChamp = stringLineToAnalyse.substr(positionCharOld, positionCharNew-positionCharOld);
cout << "le contenu de la string entre separateur est " << contenuLocalChamp << endl; // CONTENT BEATWEEN 2 SEPARATOR
localStringVector.push_back(contenuLocalChamp);
}
else
{
cout << "ce champ vide" << endl; // EMPTY FIELD
}
positionCharOld = positionCharNew+1;
}
else
{
finDelaBoucle = true;
system("PAUSE");
cout << "fin de la boucle" << endl; // END OF THE LOOP
system("PAUSE");
}
}
}
else
{
cout << "pas de fichier" << endl;
system("PAUSE");
}
return 0;
}
答案 0 :(得分:4)
整个示例与问题无关:如何逐行读取文件
std::string s;
while (std::getline(file, s))
{
std::cout << s << "\n"; // each next line printed
}
请注意使用std::getline
比干预char[]
更安全
while(std::getline(file, stringLineToAnalyse))
{
会在示例代码中找到重点
答案 1 :(得分:0)
假设您尝试阅读的文件格式正确或多或少,您很可能希望使用std::getline
中定义的<string>
函数。请记住,这与调用char数组上运行的getline
类的成员函数std::basic_istream
不同。
这一切都归结为类似的东西 - 下面的代码用文件中找到的每一行填充向量:
#include <string>
#include <fstream>
#include <vector>
int main()
{
std::ifstream myfile("/etc/passwd",std::ios::in);
if(!myfile.good()) return 1;
std::vector<std::string> myfile_lines;
std::string single_line;
while(std::getline(myfile,single_line))
{
myfile_lines.push_back(single_line);
}
myfile.close();
}