【问题标题】:How do i compare two text files in c++如何在 C++ 中比较两个文本文件
【发布时间】:2020-05-12 09:57:37
【问题描述】:

好的,我到处搜索,但无法找到它所以..

  1. 我正在做一个图书馆系统,图书馆员输入他的用户名,程序会检查他是否是图书馆员之一
  2. 我在比较部分卡住了,我尝试使用 getline 但它给了我一个错误,尝试了 get_s 并使用 char 数组而不是字符串,但仍然没有工作

请帮我做我应该做的事

using namespace std;
#include <iostream>
#include <string>
#include <fstream>

int main()
{
    //opening files
    ifstream readUsername;
    ofstream enterUsername;
    //variables
    string existUsername;
    string enteredUsername;
    //reading files
    readUsername.open("librarian usernames.txt");
    if (readUsername.fail())
    {
        cout << "can't open file" << endl;
    }
    enterUsername.open("entered librarian username.txt");
    if (enterUsername.fail())
    {
        cout << "can't open file" << endl;
    }
    while(!readUsername.eof)
    {       
        readUsername >> existUsername;
    }
    enterUsername << enteredUsername;

    readUsername.close();
    enterUsername.close();
    enterUsername.clear();

    system("pause");
    return 0;
    }

【问题讨论】:

  • while(!readUsername.eof) 不应编译。它应该是while(!readUsername.eof()) - 但请注意,这是错误的检查方式,因为直到您尝试读取EOF 之外的之后 才会设置eof 位。改为:while(readUsername &gt;&gt; existUsername) { ... }
  • 循环将按照当前编写的方式读取文件中的所有字符串,然后将最后一个字符串放入enterUsername 流中。没有进行比较。

标签: c++ string string-comparison


【解决方案1】:
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
ifstream infile;
infile.open("listOfWords.txt"); //open file

for(string listOfWords; getline(infile, listOfWords, '.'); ) //read sentences including
//spaces

cout<<listOfWords; //this displays

return 0;
}

这向您展示了如何输出文本,因此您应该将两个文件保存到一个变量中,然后比较变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 2015-07-08
    • 1970-01-01
    相关资源
    最近更新 更多