使用向量将字符串从C 中的文件转换

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

本文关键字:文件 转换 向量 字符串      更新时间:2023-10-16

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

#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"(两个单词之间的空间(?

指出用户4581301,>>将自动跳过任何空格。您可以使用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也可以被视为不良练习。

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