C++ 在cout中将行表单文件与自定义文本组合时出现问题

C++ 在cout中将行表单文件与自定义文本组合时出现问题,c++,c++11,visual-c++,c++14,C++,C++11,Visual C++,C++14,我在组合getline中的字符串和cout中的其他字符串时遇到问题,我一直在搜索答案,但我找不到有类似问题的人。我的代码是: file.open ("list.txt"); getline(file, line); int i=0; do { getline(file, line); dummyStudent.name = line; cout << "Is " << flush <&l

我在组合getline中的字符串和cout中的其他字符串时遇到问题,我一直在搜索答案,但我找不到有类似问题的人。我的代码是:

file.open ("list.txt");
    getline(file, line);
    int i=0;
    do
    {
        getline(file, line);
        dummyStudent.name = line;
        cout << "Is " << flush << dummyStudent.name << flush << " present?" << endl;
        students.push_back(dummyStudent);
        i++;
    }
    while(!file.eof());
    file.close();
但我得到的却是:

 present?udent

循环的最后一次迭代显示了正确的文本。

让我在这里猜一猜。您的文件是在Windows上创建或编辑的,但您没有使用Windows生成/运行代码。因此,不是每行末尾的换行符(
\n
),而是换行符和回车:
\r\n
。但是,文件的最后一行没有换行符(因此也没有回车符),所以只有这一行看起来不错。我说得对吗

回车符将使光标返回到行首。因此,您在
student\r
中读取,然后
std::cout
写入
Is student
,看到回车符并将光标移回行的开头,然后在那里写入
present?
。导致
出现?学生

名称
字符串末尾去掉空格(借助于来自的代码)

静态内联void rtrim(std::string&s){
s、 擦除(std::find_if(s.rbegin(),s.rend(),[](int-ch){
return!std::isspace(ch);
}).base(),s.end());
}
int main(){
//...
getline(文件,行);
dummyStudent.name=行;
rtrim(dummyStudent.name);

我能相信这是你的问题吗?@Kai看起来不像。这个
cout
语句中的所有内容都是相互独立的,所以这里不应该有UB,因为这里有序列点。可能是因为回车(
\r
)在每一行的末尾,除了最后一行之外?你能检查一下
getline
的结果,看看它是否为
false
?请创建一个在windows上以文本模式打开的文件不应该是问题。应该只在二进制模式下有问题,或者在其他平台上读取windows文件。我想我只是假设它们在Linux@Alan上。我有edited明确假设他们不是在Windows上构建/运行的。很好!问题被标记为visual c++,所以我假设他们是在Windows上。虽然我的文件是在Windows上编辑的,但我在一个mac@Bruno在这种情况下,我会在您的文件中运行类似的内容:
 present?udent
static inline void rtrim(std::string &s) {
    s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
        return !std::isspace(ch);
    }).base(), s.end());
}

int main() {
    //...
    getline(file, line);
    dummyStudent.name = line;
    rtrim(dummyStudent.name);
    cout << "Is " << flush << dummyStudent.name << flush << " present?" << endl;
    //...