我有一個名為的檔案position.txt,該檔案已以特定方式格式化。這是 position.txt 的內容:
START POLYMER 1
1 0 0
2 0 0
3 0 0
4 0 0
4 1 0
5 1 0
5 0 0
6 0 0
END POLYMER 1
但是,當我查看position.txt使用 vi 時,我看到了:

當我positions.txt在 sublime 中查看時,我看到:

很明顯,似乎在 Sublime 中添加了一條額外的行,在 Vi 中甚至不可見。這應該不是問題,但我正在運行以下代碼:
int Grid::ExtractNumberOfPolymers(std::string filename){
std::regex start("START");
std::regex end ("END");
std::ifstream myfile (filename);
if ( !myfile ){
std::cerr << "File named " << filename << " could not be opened!" << std::endl;
exit(EXIT_FAILURE);
}
std::string myString;
// std::vector <std::string> StartContents;
// std::vector <std::string> EndContents;
int numberOfStarts {0}, numberOfEnds {0};
if (myfile.is_open() && !myfile.eof() ) {
while (myfile.good()) {
std::getline(myfile, myString); // pipe file's content into stream
if (std::regex_search(myString, start)){
numberOfStarts ;
}
else if (std::regex_search(myString, end)){
numberOfEnds ;
}
else if ( myString.empty()){
std::cerr << "ERROR: Empty line found. Bad positions file. " << std::endl;
exit (EXIT_FAILURE);
}
}
}
if (numberOfStarts==numberOfEnds){
return numberOfStarts;
}
else {
std::cerr << "Number of starts is not the same as number of ends. Bad input file." << std::endl;
return 0;
}
}
當我運行此代碼時,我正在退出
std::cerr << "ERROR: Empty line found. Bad positions file. " << std::endl;
exit (EXIT_FAILURE);
錯誤。在打開positions.txt 并洗掉最后一行之前,我無法找到錯誤。這里出了什么問題?為什么 Vim 會顯示這樣的東西?
我需要空行錯誤訊息,因為我不希望輸入檔案中斷。我希望每一行的坐標不會破壞代碼的其他部分。
Any advice you have for me will be appreciated.
edit: using xxd on positions.txt, I get the following
[faraway_server] src $ xxd positions.txt
00000000: 5354 4152 5420 504f 4c59 4d45 5220 310a START POLYMER 1.
00000010: 3120 3020 3020 0a32 2030 2030 0a33 2030 1 0 0 .2 0 0.3 0
00000020: 2030 0a34 2030 2030 0a34 2031 2030 0a35 0.4 0 0.4 1 0.5
00000030: 2031 2030 0a35 2030 2030 200a 3620 3020 1 0.5 0 0 .6 0
00000040: 3020 0a45 4e44 2050 4f4c 594d 4552 2031 0 .END POLYMER 1
00000050: 0a
What should I do next?
uj5u.com熱心網友回復:
在\n帶有文本的最后一行之后只有一個換行符 ( ),因此您讀取一個空行的事實是由于程式中的錯誤。
這:
while (myfile.good()) {
std::getline(myfile, myString);
應該是這樣的:
while (std::getline(myfile, myString)) {
請參閱為什么iostream::eof()在回圈條件內(即while (!stream.eof()))被認為是錯誤的?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/388775.html
標籤:c vim sublimetext3 text-editor ifstream
下一篇:如何按列值過濾矩陣的行?
