【问题标题】:Reverse a string from a file in c++ using vectors使用向量从c ++中的文件中反转字符串
【发布时间】:2018-04-24 23:15:35
【问题描述】:

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

#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”(两个单词之间有空格)?

【问题讨论】:

  • 使用 std::getline 读取输入。
  • &gt;&gt; 默认行为是将空格视为不需要的并为您丢弃。通常非常有帮助。不过,在这种情况下就没那么有用了。
  • 您的代码是否在没有#include&lt;algorithm&gt; 的情况下运行?

标签: c++ string vector char reverse


【解决方案1】:

正如 user4581301 所指出的,&gt;&gt; 将自动跳过任何空格。您可以通过使用std::noskipws 流操纵器并将file&gt;&gt;i 更改为file&gt;&gt;std::noskipws&gt;&gt;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

【讨论】:

    【解决方案2】:

    reverse 函数工作正常,问题出在:

    while(file>>i){
    

    std::operator&gt;&gt; 跳过空格和换行符,您需要使用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
    

    【讨论】:

      猜你喜欢
      • 2010-12-02
      • 2023-03-28
      • 1970-01-01
      • 2020-09-04
      • 2015-06-02
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多