为什么 std::getline() 的结果不符合预期

Why result from std::getline() is not as expected

我正在从文本文件中提取一些数据并将它们放入 2 个向量中,但 std::getline() 的输出与我预期的不同。这是代码:

std::vector<std::string> v1;
std::vector<std::string> v2;

const char* filename = "words.txt";
std::ifstream fin(filename);
  
if (!fin) {
    throw "Bad file name!";
}
else {
    // File is good
    std::string temp;
    while (std::getline(fin, temp)) {
      std::cout << "(((Temp: " << temp << ")))" << std::endl;
      v1.push_back(temp.substr(0, temp.find(' ')));
      // Erase first character
      temp.erase(0, temp.find(' ') + 1);
      // Erase spaces
      v2.push_back(temp.substr(temp.find_first_not_of(' '),temp.find_last_not_of(' ') - temp.find_first_not_of(' ') + 1));
    }
}

// output v1:
std::cout << "\nValues of v1:\n";
for (auto word : v1){
   std::cout << "(((" << word << ")))" << std::endl;
}

// output v2:
std::cout << "\nValues of v2:\n";
for (auto word : v2){
   std::cout << "(((" << word << ")))" << std::endl;
}

这是“words.txt”:

a    A
b        B
c    C
d         D
e       E

真正的words.txt更复杂但相似。

这是输出:

)))Temp: a    A
)))Temp: b        B
)))Temp: c    C
)))Temp: d         D
)))Temp: e       E

Values of v1:
(((a)))
(((b)))
(((c)))
(((d)))
(((e)))

Values of v2:
)))A
)))B
)))C
)))D
)))E

为什么从文件读取的每一行的输出和两个向量之间的输出不同?

v2 中,值以回车符 return (\r) 结尾。当它被打印到终端时,它使光标回到行首,因此 ))) 被打印在 ((( 之上。当显示 temp 值时会发生同样的事情,因为它会显示整行。

另请参见Getting std :: ifstream to handle LF, CR, and CRLF?