1

I'm trying to write a program that reads a text from a file (only strings) and reverse it. The following code does that, but it doesn't take into account spaces between words:

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

If the text on the file is "dlroW olleH", the program would print out "HelloWorld". What can I do so that it prints "Hello World" (with the space between both words)?

Abhishek Keshri
  • 3,074
  • 14
  • 31

2 Answers2

2

The reverse function is working perfectly fine, the problem lies here:

while(file>>i){

std::operator>> skips spaces and new lines, you will need to use std::istream::getline to avoid this or try std::noskipws manipulator.

Usage:

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

Output:

123
  1
Abhishek Keshri
  • 3,074
  • 14
  • 31
2

As user4581301 pointed out, >> will automatically skip any whitespace. You can disable this by using the std::noskipws stream manipulator and changing file>>i to file>>std::noskipws>>i. A better solution altogether is to simply use std::getline to read the whole string into an std::string, reverse it, and print it out instead handling the characters individually.

#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
int main()
{
    std::ifstream file("input.txt");
    //insert error checking stuff here
    std::string line;
    std::getline(file, line);
    //insert error checking stuff here
    std::reverse(line.begin(), line.end());
    std::cout << line << '\n';
}

Just a note about your code, you should declare variables only when they are used. For example, your variable x is only used at the end of the program, but it is declared all the way at the top. using namespace std can also be considered bad practice.

eesiraed
  • 4,626
  • 4
  • 16
  • 34