我有一个包含的文本文件
//range of X
X=1-5
//range of Y
Y=1-5
我如何读取文件,使其忽略注释和空行并获取以下输出:
X = 1-5
Y = 1-5
int main(){
string fileName,X;
cout << "Please enter filename: " ;
cin >> fileName;
ifstream infile;
infile.open(fileName);
if (!infile){
cerr << "Error opening : " << fileName << ", file does not exist" << endl;
return -1;
}
while(getline(infile, X)){
cout << X;
}
infile.close();
return 0;
}
答案 0 :(得分:1)
根据您的问题,注释始终使用运算符“ //”放在单独的行上。
if(X.size() == 0 || (X.size() >= 2 && X[0] == '/' && X[1] == '/')){
continue;
}
答案 1 :(得分:-1)
替换
while(getline(infile, X)){
cout << X;
}
通过
while(getline(infile, X)){
if((X.size() >=2 && X.substr(0,2) != "//") && X.find_first_not_of(' ') == X.npos) cout << X;
}
用于存储两行的编辑:
通过以下内容替换您的while
vector<string> twoStrings;
while(getline(infile, X)){
if((X.size() >=2 && X.substr(0,2) != "//") && X.find_first_not_of(' ') == X.npos)
{
cout << X;
twoStrings.push_back(X);
}
}
//Now the first line is stored in twoStrings[0] and the second line is stored in twoStrings[1]