C++读取多个文件的方法

How to read multiple files on C++

我的问题是:

First read a file named symbols.txt. This file consist of many lines, each line consist of 2 elements : an uppercase letter and a string, this file is ended by a hash(#).

Second read a file named dict.txt. This file consist of many words(string) . Ended by a hash(#)

Third read a file named handin.txt. This file consist of some numbers which you're gonna working on it. Ended by a hash(#)

Print your output in a file named handout.txt

这是我的代码,但我不确定我是否正确阅读了输入内容。请帮我检查一下。非常感谢。

#include<bits/stdc++.h>
using namespace std;

int main() {

    freopen("symbols.txt" , "r" , stdin);

         //  input the letter and the string 

    char X ; string Y ;

    while(cin >> X >> Y && X != '#' )  {
         // my code goes here
    }

    freopen("dict.txt" , "r" , stdin) ;

          // input the strings here 

    freopen("handin.txt", "r" , stdin);

         // input the numbers here


    / *

          Here is my code 

    * /

    freopen("handout.txt" , "w" , stdout);

    // let in print the output here



}
#include<bits/stdc++.h>

不要这样做。


using namespace std;

也不要这样做。 Here's why


freopen("symbols.txt" , "r" , stdin);

这很糟糕!您正在使用 std::freopen to associate a file with stdin. Then later on, you're using std::cin 从文件中读取。您正在做的事情非常 "hacky",这有时可能会奏效,但并非总是如此。 stdin(来自 C)和 std::cin(来自 C++)不需要像这样链接。 freopen 是 C API 所以你不应该在 C++ 中使用它。

您应该做的是打开一个输入文件流 (std::ifstream) 并从中读取。这可能看起来有点像这样:

#include <string> // std::string
#include <fstream> // std::ifstream std::ofstream
#include <iostream> // std::cerr

int main() {
  std::ifstream symbols("symbols.txt");
  if (!symbols.is_open()) {
    // There was a problem opening the symbols file
    // Maybe it was missing
    // You should end the program here and write an error message
    std::cerr << "Failed to open \"symbols.txt\"\n";
    // returning an error code of 0 means "everything is fine"
    // returning anything else means "something went wrong"
    return 1;
  }

  // Try to choose more descriptive names than "X" and "Y"
  char X;
  std::string Y;
  while (symbols >> X >> Y && X != '#') {
    // ...
  }

  // ...
}

如果您为每个打开的文件创建一个新的 std::ifstream(而不是重复使用同一个文件),您的代码会更清晰。错误检查很重要。您应该确保在使用文件之前检查该文件是否实际打开。要将输出写入 "handout.txt",您可以使用输出文件流 (std::ofstream)。


有些事情可能会让您失望。拿这个 "symbols.txt" 文件:

A many words
B on the same line
C could cause problems
#

如果我们尝试使用当前代码读取它,我们 运行 会遇到麻烦:

symbols >> X >> Y;
// X is 'A'
// Y is "many" rather than "many words" as you might expect

如果每行只有一个词,那么这应该不是问题,但如果有多个词,那么您可能需要使用 std::getlinestd::getline 言出必行。它读取整行并将其写入给定的字符串。

你会像这样使用它:

while (symbols >> X && X != '#' && std::getline(symbols, Y)) {
  // ...
}

在从 Whosebug 复制代码之前,请确保您理解代码(阅读一些链接)。