提问者:小点点

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


我正在运行以下程序

#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;
}

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

permission
copper
operation
cop
rationale
rest

在terminal中得到以下输出

permission
copper
operation
cop
rationale
rest

 rest and last word: permission

为什么最后一个单词words.back()打印在行首,同时擦除部分文本?


共1个答案

匿名用户

因为您的文件有Windows的行尾(“\r\n”),而您在Linux或Mac上(它不会将这些行尾翻译成“\n”)。

std::getLine只是为您修剪'\n's。 因此,\r留在每个字符串的末尾; 在许多控制台中,'\r'将写入光标移动到行的开头。 然后,“”<<<; words.back()部分覆盖已经编写的“first and last word:”<<; Words[0]部分。

  • 第一个单词是权限
  • 最后一个单词是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     │
│                   │  ꕯ                                   │
└───────────────────┴──────────────────────────────────────┘

您可以自己将其从每行末尾剥离出来,也可以在外部对文件进行预处理。