var str = "some text{index:1}{id:2}{value:3}";
var index = str.match(/{index:(\d+)}/);
index = index && index[1]*1;
Мне плохо, что я не сразу это увидел.
int numLines = lineCount(inFile);
возвращает правильное количество строк в файле. Жука здесь нет, чувак.
std::string data[numLines];
Не является кошерным C ++, но создаст массив с элементом для каждой строки в файле, если поддерживается. Ваша программа запущена, поэтому она поддерживается. Тем не менее, предпочтительнее использовать библиотечные контейнеры .
Между тем в readFile
...
while(std::getline(inFile, data[i]))
Попробую прочитать строку в data[i]
. Независимо от того, успешно ли выполняется чтение, должен быть data[i]
для чтения. Не будет последней попытки.
Логика
getline
отвести взгляд от конца data
на string
и идущий бум (в частности, неопределенное поведение , которое проявляется как идущий бум), потому что его нет. [1119 ] int main(){
std::ifstream inFile("input.txt");
// no longer need. Vector keeps track for us
// int numLines = lineCount(inFile);
std::vector<std::string> data;
// read nothing from file. Don't need to rewind
readFile(inFile, data);
// note: files close themselves when they are destroyed.
//inFile.close();
return 0;
}
void readFile(std::istream& inFile, std::vector<std::string> & data){
int i = 0;
std::string line; // line to read into. Always there, so we don't have to worry.
while(std::getline(inFile, line)){
std::cout << i << "\n"; //testing values
std::cout << line << "\n"; //testing values
data.push_back(line); // stuff line into vector.
i++;
}
}
vector
int main(){
std::ifstream inFile("input.txt");
int numLines = lineCount(inFile);
// legal in every C++, but prefer container may want some extra armour
// here to protect from numlines 0.
std::string * data = new std::string[numlines];
// the following is a faster way to rewind a file than closing and re-opening
inFile.clear(); // clear the EOF flag
inFile.seekg(0, ios::beg); // rewind file.
readFile(inFile, data);
inFile.close();
return 0;
}
void readFile(std::istream& inFile, std::string * data){
int i = 0;
std::string line; // same as above. line is here even if data[i] isn't
while(std::getline(inFile, line)){
std::cout << i << "\n"; //testing values
std::cout << line << "\n"; //testing values
data[i] = line; // stuff line into array. Smart compiler may realize it can move
//if not, c++11 adds a formal std::move to force it.
i++;
}
}