我正在运行以下程序
#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()
打印在行首?
最佳答案
因为您的文件有 Windows 行尾 ( "\r\n"
) 而您在 Linux 或 Mac 上(不会将这些转换为 "\n"
)。
std::getline
只修剪 '\n'
是给你的。所以,\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 .
关于c++ - 从文本文件 : weird behaviour 中读取单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63248485/