c++ - 使用向量从c ++中的文件中反转字符串
问题描述
我正在尝试编写一个从文件(仅字符串)中读取文本并将其反转的程序。以下代码可以做到这一点,但它没有考虑单词之间的空格:
#include<iostream>
#include<vector>
#include<fstream>
using namespace std;
int main(){
ifstream file("file.txt");
char i;
int x;
vector<char> vec;
if(file.fail()){
cerr<<"error"<<endl;
exit(1);
}
while(file>>i){
vec.push_back(i);
}
x=vec.size();
reverse(vec.begin(), vec.end());
for(int y=0; y<x; y++){
cout<<vec[y];
}
return 0;
}
如果文件上的文本是“dlroW olleH”,程序将打印出“HelloWorld”。我该怎么做才能打印“Hello World”(两个单词之间有空格)?
解决方案
该reverse
功能运行良好,问题出在:
while(file>>i){
std::operator>>
跳过空格和换行,您需要使用std::istream::getline
来避免这种情况或尝试使用std::noskipws
操纵器。
用法:
#include <iostream> // std::cout, std::skipws, std::noskipws
#include <sstream> // std::istringstream
int main () {
char a, b, c;
std::istringstream iss (" 123");
iss >> std::skipws >> a >> b >> c;
std::cout << a << b << c << '\n';
iss.seekg(0);
iss >> std::noskipws >> a >> b >> c;
std::cout << a << b << c << '\n';
return 0;
}
输出:
123
1
推荐阅读
- java - 如何使用键盘快捷键在 Eclipse IDE 中运行代码
- quartz-scheduler - 石英调度程序根据重复触发完成作业的事件
- wordpress - 从 AWS Bitnami Wordpress 中的子目录提供静态 html 文件
- python - 如何使用 Python 将 6GB JSON 文件转换为 CSV?
- java - QuickFIX/J - 性能基准
- angular - Angular - 错误 TS2554:预期 1 个参数,但得到 0
- javascript - 在 JavaScript 中,“Uncaught SyntaxError: Identifier 'X' has been declared”是什么意思?
- sql - Postgres - 用户定义的订单序列
- ajax - 如何在附加jquery代码相同的laravel图像中动态图像
- php - 有条件地在 woocommerce 产品页面上显示变体描述