使用向量从c ++中的文件中反转字符串

Reverse a string from a file in c++ using vectors

我正在尝试编写一个程序,从文件(仅字符串)中读取文本并将其反转。下面的代码就是这样做的,但它没有考虑单词之间的 spaces:

#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"(两个词之间有 space)?

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

正如 user4581301 指出的那样,>> 会自动跳过任何空格。您可以通过使用 std::noskipws 流操纵器并将 file>>i 更改为 file>>std::noskipws>>i 来禁用此功能。一个更好的解决方案是简单地使用 std::getline 将整个字符串读入 std::string,反转它,然后打印出来,而不是单独处理字符。

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

请注意您的代码,您应该仅在使用变量时声明变量。比如你的变量 x 只在程序末尾使用,却在最顶部一路声明。 using namespace std 也可以是 considered bad practice.