简体   繁体   English

使用包含字符和数字的c ++读取文件

[英]Reading a file with c++ containing chars and numbers

I have a text file containing sort of a graph presentation, as such: 我有一个包含某种图形表示形式的文本文件,例如:

7 7

{5, 2, 3}, {1,5}, { }, { }, {3}, { }, { } {5,2,3},{1,5},{},{},{3},{},{}

Now, I know how to read a file and get in into an int 现在,我知道如何读取文件并进入int

    while ((n = myfile.get()) != EOF) 

or into a string line by line 或一行一行地

    getline (myfile,line)

The problem I have, is that with both of these options I can't really seem to compare every character I extract and check if it's a number or a "," or "{" or "}". 我的问题是,使用这两个选项,我似乎无法真正比​​较提取的每个字符并检查它是数字还是“,”或“ {”或“}”。 Is there a simple way of doing that? 有一个简单的方法吗? I've been banging my head with this for hours since yesterday. 从昨天开始,我已经为此动了好几个小时。 I've tried some isdigit and casting, but that didn't work for me as well and really complicated stuff. 我已经尝试了一些等角线和强制转换,但这对我也不起作用,而且真的很复杂。

The easiest solution, I think, would be to get your hands dirty a bit, by reading the file char by char. 我认为,最简单的解决方案是通过逐个读取char文件来使您的手有点脏。 I suggest you store the sets in a vector of vectors of int s (visualize it like a 2D array, a matrix, if you like). 我建议您将集合存储在int向量的向量中(如果需要,可以像2D数组一样可视化它)。

If the i-th set is empty, then the i-th vector will be empty too. 如果第i个集合为空,则第i个向量也将为空。

In the loop in which you will parse the characters, you will skip the opening curly braces and commas. 在解析字符的循环中,将跳过开头的花括号和逗号。 You will do similarly for the closing curly braces, except from the fact that you would need to update an index, which will help us update the index-th vector. 对于右花括号,您将执行类似的操作,除了需要更新索引这一事实之外,这将有助于我们更新第index个向量。

When we actually read a digit, then you can convert a char to an int . 当我们实际读取数字时,可以将char转换为int

Complete example: 完整的例子:

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

int main(void) {
    char ch;
    fstream fin("test.txt", fstream::in);
    if(!fin) {
        cerr << "Something is wrong...! Exiting..." << endl;
        return -1;
    }
    int N; // number of sets
    fin >> N;
    vector<vector<int> > v;
    v.resize(N);
    int i = 0;
    while (fin >> ch) {
            //cout << ch << endl;
        if(ch == '{' || ch == ',')
            continue;
        if(ch == '}') {
            i++;
            continue;
        }
        v[i].push_back(ch - '0');
    }
    if(i == N) {
        cout << "Parsing the file completed successfully." << endl;
    } else {
        cout << "Parsed only " << i << " sets, instead of " << N << endl;
    }
    for(size_t i = 0; i < v.size(); ++i) {
        if(v[i].size() == 0)
            cout << i + 1 << "-th set is empty\n";
        else {
            for(size_t j = 0; j < v[i].size(); ++j)
                cout << v[i][j] << " ";
            cout << endl;
        }
    }
    return 0;
}

Output: 输出:

gsamaras@aristotelis:/Storage/homes/gsamaras$ g++ main.cpp gsamaras @ aristotelis:/存储/房屋/ gsamaras $ g ++ main.cpp

gsamaras@aristotelis:/Storage/homes/gsamaras$ ./a.out 
Parsing the file completed successfully.
5 2 3 
1 5 
3-th set is empty
4-th set is empty
3 
6-th set is empty
7-th set is empty

Important note: This should serve as a starting point, since it won't treat numbers that have more than one digits. 重要说明:这应该作为一个起点,因为它不会处理多于一个数字的数字。 In this case, you will to read up to the comma, or the closing curly brace, to make sure that you read all the digits of the numbers, then convert from string to integer, and then store it in the corresponding vector. 在这种情况下,您将阅读逗号或大括号,以确保您阅读数字的所有数字,然后从字符串转换为整数,然后将其存储在相应的向量中。

Its better to read character by character as follows: 最好逐个字符地读取,如下所示:

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

int main()
{
    string line;
    int lineNum = 0;
    ifstream myfile ("file.txt");
    if (myfile.is_open())
    {
        while ( getline (myfile, line) )
        {
            // Identifying the type of charcter
            char a;
            cout << "Line Number " << ++lineNum << ": ";
            for(int i = 0; i < line.length(); i++)
            {
                a = line[i];
                cout << "\n\t" << a;
                if((a >= 32 && a <= 47) || (a >= 58 && a <= 64) || (a >= 91 && a <= 96) || (a >= 123 && a <= 126))
                {
                    cout << "\t(This character is either a Punctuation or arithmetic mark.)";
                    // If you don't want to porcess these character, then you may 'continue' to the next sub string
                }
                else if(a >= 48 && a <= 57)
                {
                    cout << "\t(This character is a number.)";
                    // If you want to change the number ot int, you can use atoi or stoi
                }
                else if(a >= 65 && a <= 90)
                    cout << "\t(Capital letter)";
                else if(a >= 97 && a <= 122)
                    cout << "\t(Small letter)";

            }
            cout<<endl;
        }
        myfile.close();
    }
    else
        cout << "Unable to open file";
    return 0;
}

I hop this helps. 我希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM