我正在运行以下程序
#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我在终端中得到以下输出
permission
copper
operation
cop
rationale
rest
rest and last word: permission为什么在删除部分文本时,最后一个单词words.back()会打印在行的开头?
发布于 2020-08-04 14:04:02
因为您的文件有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 │
│ │ ꕯ │
└───────────────────┴──────────────────────────────────────┘解决方案
or preprocess the file externally,您可以自己从每一行的末尾删除它。
https://stackoverflow.com/questions/63248485
复制相似问题