我需要转换一些代码,以便它适用于输入和输出文件文本

I need to convert some code so that it works with an input and output file text

本文关键字:输入 适用于 输出 文本 文件 转换 代码      更新时间:2023-10-16

我有一个程序,可以反转句子中的字母,但保持单词的顺序相同。我需要将代码从iostream库更改为fstream库,其中用户将句子输入输入文件("input.txt"(,程序将相反的输出到输出文本文件中。

输入示例:

This problem is too easy for me. I am an amazing programmer. Do you agree?

输出示例:

sihT melborp si oot ysae rof em. I ma na gnizama remmargorp. oD uoy eerga?

我已经有的代码:

int main()
{
    int i=0, j=0, k=0, l=0;
    char x[14] = "I LOVE CODING";
    char y[14] = {''}; 
    for(i=0; i<=14; i++) { 
        if(x[i]==' ' || x[i]=='')  {
            for(j=i-1; j>=l; j--) 
            y[k++] = x[j];
            y[k++] = ' ';  
            l=i+1;
         }
    } 
    cout << y;
    return 0;
}

我会使用 std::string 来存储字符串,并从std::vectorconst_iterator中受益,以更好地利用C++功能:

#include <string>
#include <vector>
int main()
{
  std::string s("This problem is too easy for me. I am an amazing programmer. Do you agree?");
  const char delim = ' ';
  std::vector<std::string> v;
  std::string tmp;
  for(std::string::const_iterator i = s.begin(); i <= s.end(); ++i)
  {
    if(*i != delim && i != s.end())
    {
      tmp += *i;
    }else
    {
      v.push_back(tmp);
      tmp = ""; 
    }
  }
  for(std::vector<std::string>::const_iterator it = v.begin(); it != v.end(); ++it) 
  {
    std::string str = *it,b;
    for(int i=str.size()-1;i>=0;i--)
      b+=str[i];
    std::cout << b << " ";
  }
  std::cout << std::endl;
}

输出:

sihT melborp si oot ysae rof .em I ma na gnizama .remmargorp oD uoy ?eerga

您提交的代码看起来更像是来自 C 而不是来自 C++ 的代码。 不确定您是否熟悉 std::string 和函数调用。 由于您编写的代码非常复杂,因此我假设您是。

下面是如何使用 fstream 的示例。 我几乎总是得到输入的线,因为我发现它让我遇到的问题更少。

然后,我几乎总是使用stringstream来解析行,因为它整齐地拆分了每个空格的行。

最后,我尝试找出一个 while(( 或 do{}while((; 循环,它将触发来自 getline(( 调用的输入。

请注意,如果单词以标点符号结尾,为了将标点符号保留在末尾,reverse_word(( 函数必须在末尾查找非字母字符,然后将其保存到一边。 这可以通过仅反转 alpha 运行来完成。

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
///////////////////
/// return true if ch is alpha
/// return false for digits, punctuation, and all else
bool is_letter(char ch){
  if((ch >= 'A' && ch <= 'Z') ||
      (ch >= 'a' && ch <= 'z')) {
    return true;
  } else {
    return false;
  }
}
////////
// Only reverse the letter portion of each word
//
std::string reverse_word(std::string str)
{
  std::string output_str; // Probably have to create a copy for output
  output_str.reserve(str.length()); // reserve size equal to input string
  // iterate through each letter of the string, backwards,
  // and copy the letters to the new string
  char save_non_alpha = 0;
  for (auto it = str.rbegin(); it != str.rend(); it++) {
    /// If the last character is punctuation, then save it to paste on the end
    if(it == str.rbegin() && !is_letter(*it)) {
      save_non_alpha = *it;
    } else {
      output_str += *it;
    }
  }
  if(save_non_alpha != 0) {
    output_str += save_non_alpha;
  }
  return output_str;  // send string back to caller
}
int main()
{
  std::string input_file_name{"input.txt"};
  std::string output_file_name{"output.txt"};
  std::string input_line;
  std::ifstream inFile;
  std::ofstream outFile;
  inFile.open(input_file_name, std::ios::in);
  outFile.open(output_file_name, std::ios::out);
  // if the file open failed, then exit
  if (!inFile.is_open() || !outFile.is_open()) {
    std::cout << "File " << input_file_name
        << " or file " << output_file_name
        << " could not be opened...exitingn";
    return -1;
  }

  while (std::getline(inFile, input_line)) {
    std::string word;
    std::string sentence;
    std::stringstream stream(input_line);
    // I just like stringstreams.  Process the input_line
    // as a series of words from stringstream.  Stringstream
    // will split on whitespace.  Punctuation will be reversed with the
    // word that it is touching
    while (stream >> word) {
      if(!sentence.empty())  // add a space before all but the first word
        sentence += " ";
      word = reverse_word(word);
      sentence += word;
    }
    outFile << sentence << std::endl;
  }
  inFile.close();
  outFile.close();
  return 0;
}