从文本文件中读取单词:奇怪的行为

jro*_*roy 3 c++

我正在运行以下程序

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main(int argc, char *argv[])
{
    ifstream input_file(argv[1]);
    vector<string> words;
    string line;

    while(getline(input_file, line))
    {
        cout << line << endl;
        words.push_back(line);
    }
    input_file.close();

    cout << "First and last word: " << words[0] << " " << words.back() << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用以下文本文件作为输入

permission
copper
operation
cop
rationale
rest
Run Code Online (Sandbox Code Playgroud)

我在终端中得到以下输出

permission
copper
operation
cop
rationale
rest

 rest and last word: permission

Run Code Online (Sandbox Code Playgroud)

为什么words.back()在擦除某些文本时将最后一个字打印在行首?

Ast*_*ngs 6

因为您的文件具有 Windows 行尾 ( "\r\n") 并且您使用的是 Linux 或 Mac(不会将它们转换为"\n")。

std::getline只是'\n'为你修剪s。所以,\r留在每个字符串的末尾;在许多控制台中,'\r'将写入光标移动到行首。然后,该" " << words.back()部分覆盖已写入的"First and last word: " << words[0]部分。


例子:

  • 第一个字是 permission?
  • 最后一句话是 rest?

(注意?每个单词末尾的控制字符!)

????????????????????????????????????????????????????????????
?                   ?  ?????                               ?
? Write "First"     ?  First                               ?
?                   ?       ?                              ?
????????????????????????????????????????????????????????????
?                   ?       ????                           ?
? Write " and"      ?  First·and                           ?
?                   ?           ?                          ?
????????????????????????????????????????????????????????????
?                   ?           ?????                      ?
? Write " last"     ?  First·and·last                      ?
?                   ?                ?                     ?
????????????????????????????????????????????????????????????
?                   ?                ??????                ?
? Write " word:"    ?  First·and·last·word:                ?
?                   ?                      ?               ?
????????????????????????????????????????????????????????????
?                   ?                      ????????????    ?
? Write first word  ?  First·and·last·word:·permission     ?
?                   ?  ?                                   ?
????????????????????????????????????????????????????????????
?                   ?  ?                                   ?
? Write " "         ?  ·irst·and·last·word:·permission     ?
?                   ?   ?                                  ?
????????????????????????????????????????????????????????????
?                   ?   ?????                              ?
? Write last word   ?  ·rest·and·last·word:·permission     ?
?                   ?  ?                                   ?
????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

解决方案

您可以自己从每一行的末尾剥离它,或者在外部预处理文件