【问题标题】:Comparing elements of text file between each other相互比较文本文件的元素
【发布时间】:2020-01-14 19:38:55
【问题描述】:

我正在尝试将三个数字的块相互比较,以制作一个新的输出文件,其中仅包含满足该条件的那些:块的第一个数字小于第二个数字且小于第三个数字,第二个数字在块必须大于第一个但小于第三个。

这是我的输入文件代码:

int main()
{
ofstream outfile ("test.txt");
outfile << "123 456 789 123 123 432 \n 123 243 " << endl;

我想把它分成三个块,比如“123”、“456”等等,以便只在新的输出文件中写入满足要求的那些。我决定将整个文件转换成一个整数向量以便能够比较它们。

char digit;
ifstream file("test.txt");
vector<int> digits;

 while(file >> digit) {
digits.push_back(digit - '0');
}

我想比较它们的方法看起来像这样:

bool IsValid(vector<int> digits){
for(int i=0; i<digits.size(); i++){
    if(digits[0] < digits[1] & digits[0] < digits[2] & digits[1]<digits[2])
    return true;

    else{
    return false;
    }
  }
}

但是这只会比较第一个块,你会做不同的吗?还是我应该继续做向量的想法

【问题讨论】:

  • 你为什么要使用vector?这是一个简单的除法和模数问题。
  • @PaulMcKenzie 还有哪些其他选择?
  • 如果您只想查看从左到右的数字是否按升序排列,则无需使用vector。这就是你对问题的描述似乎在说什么。
  • & -> && in IsValid()

标签: c++ file c++11 text


【解决方案1】:

你可以这样做。 “get”读取单个字符,当有 3 位数字时调用函数 IsValid。

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

bool IsValid(vector<int> digits)
{
    if(digits[0] < digits[1] & digits[0] < digits[2] & digits[1]<digits[2])
        return true;
    else
        return false;
}
int main()
{
    ifstream in("test.txt");
    ofstream out("output.txt");
    char tmp;
    vector<int> digits;
    while(in.get(tmp))
    {
        if(tmp!=' ' and tmp!='\n')
        {
            digits.push_back(tmp-'0');
            if(digits.size()==3)
            {
                if(IsValid(digits))
                    out<<digits[0]<<digits[1]<<digits[2]<<endl;
                digits.clear();
            }
        }
    }
    out.close();
    in.close();
}

【讨论】:

  • 我看不到 cont++ 的位置;来自
  • 我已经用 stream.close() 更新了代码。你有什么问题吗?
  • 它可以工作,但是如果我的文件是这样的 "123 456 789 123 123 432 \n 123 243 \n \n 123 "它不能识别最后的 123 我不知道为什么@多梅尼科·兰扎
  • 我的错,我移动了矢量大小的检查。如果代码有效,请考虑接受我的回答:)
【解决方案2】:

如果你的任务是:块的第一个数字小于第二个并且小于第三个,那么块中的第二个数字必须大于第一个但小于第三个 - 你是字符串类型的数字 - 排序- 使用它)) 如果数据是 3 位数字和空格分隔)))

std::stringstream ss{line}; - 例如像 fstream )))

#include <iostream> 
#include <vector> 
#include <iterator>
#include <string>
#include <sstream>
#include <algorithm>


int main() {

    std::string line{"123 456 789 123 123 432 123 243 "};
    std::cout << line << std::endl;

    std::string out_line;

    std::stringstream ss{line};
    std::string tmp_str;

    while(ss >> tmp_str) {
        if (std::is_sorted(std::begin(tmp_str), std::end(tmp_str))) {
            out_line += tmp_str + " ";
        }
    }

    std::cout << out_line << std::endl;

    return 0; 
}

【讨论】:

  • 顺便说一句,您不需要将std::string 变量设置为空字符串; std::string 构造函数会为您执行此操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 2022-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
相关资源
最近更新 更多