更新时间:2022-11-29 17:28:54
可能还有'\ n'char(或EOF,'\ 0'),你应该尝试检查字符串是否为干净。
I have a list of files stored in a text file. I read the file line by line and store them in a string array. The file list looks like this:
04_02_1310.csv
04_03_1350.csv
04_04_0421.csv
04_05_0447.csv
and so on. Let's call my string array
filelist[i]
Assuming I am trying the open the first file in the list:
inputFile.open(filelist[0].c_str()); // This cannot open file
the file cannot be opened. If i place the file name in quotation marks, everything works out fine:
inputFile.open("04_02_1310.csv"); // This works perfectly
if i print the contents of filelist[i], then it works fine as well:
cout << filelist[0] << endl; // This outputs 04_02_1310.csv on screen.
Can somebody tell me what is wrong with the approach above? This is driving me crazy for the last 2 days, and I am about the enter everything manually just to get it done (100+ files one after another).
I am also open to any other way to do this simple task.
Thanks!!!
EDIT: I am adding a relevant portion of the code if you would like to see how it is implemented:
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
//Declarations for I/O files
ifstream inputFile;
//Declare other variables (forgot to add these in my previous EDIT, sorry)
int number_of_files;
string line;
string *filelist = NULL;
//Open file list and count number of files
inputFile.clear();
inputFile.open("filelist.txt", ios::in);
//exit and prompt error message if file could not be opened
if (!inputFile){
cerr << "File list could not be opened" << endl;
exit(1);
}// end if
// count number of lines in the data file and prompt on screen
number_of_files = 0;
while (getline(inputFile, line))
number_of_files++;
cout << "Number of files to be analyzed: " << number_of_files << endl;
filelist = new string[number_of_files];
inputFile.close();
//Re-open file list and store filenames in a string array
inputFile.clear();
inputFile.open("filelist.txt", ios::in);
//exit and prompt error message if file could not be opened
if (!inputFile){
cerr << "File list could not be opened" << endl;
exit(1);
}// end if
// store filenames
i = 0;
while (getline(inputFile, line)){
filelist[i] = line;
//cout << filelist[i] << endl;
i = i + 1;
}
inputFile.close();
//open first file in the list, I deleted the loop to focus on the first element for now
inputFile.clear();
inputFile.open(filelist[0].c_str(), ios::in);
//exit and prompt error message if file could not be opened
if (!inputFile){
cerr << "Data file could not be opened" << endl;
exit(1);
}// end if
The output is:
Data file could not be opened
Thanks again!
It is possible that there still is the '\n' char (or EOF,'\0' ) from your textfile in that string, you should try checking if the strings are "clean".