首页 > 解决方案 > 使用向量从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”(两个单词之间有空格)?

标签: c++stringvectorcharreverse

解决方案


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

推荐阅读