简体   繁体   中英

Reading digits on separate lines in a txt.-file to an array in C++

In order to solve Euler Project 8 without resorting to a "Big Number" library, I would like to read the separate digits in an txt.-file to separate spots in an array. The digits in the txt.-file are arranged as follows:

094239874......29837429837 [50 of them],

192319274......12837129873 [50 of them]

such that there are in total 20 lines with 50 digits, all separated by enters. So I am trying to write a program which writes the first digits to the first spot in the array and continues this process (paying attention to the spaces) until the 1000th digit. I have tried finding solutions to this problem in tutorials and elsewhere online, but I cannot make it work for this specific example. Up to now I have something like

 int main() {

 int array[999];
 string trial[999];

 ofstream myfile;
 myfile.open ("example.txt");

 for(i=1 ; i<=1000 ; i++) {
 myfile >> trial;
 // Somehow convert string to int as well in this loop?
 }

You can read your file line by line, then add your digits to an array like this way:

// out of your loop
std::vector<int> digits;
// in your loop
std::string buffer = /*reading a line here*/;
for (auto c : buffer) {
    digits.push_back(c - '0');
}

Furthermore, STL containers are better than C-style arrays ( std::vector / std::array ).

I suppose this is what you're looking for

int main(void)
{
    unsigned char numbers[20][50];
    FILE *pf = fopen("example.txt", "r");
    for(int i = 0; i < 20; i++)
    {
        // read 50 characters (digits)
        fread(&numbers[i], 1, 50, pf);
        // skip line feed character);
        fseek(pf, 1, SEEK_SET);
    }
    fclose(pf);

    // conversion from ascii to real digits by moving the digit offset (subtracting by the first digit char in ascii table)
    for(i = 0; i < 20*50; i++)
        ((unsigned char*)numbers)[i] -= (unsigned char) '0';

    // the digits are now stored in a 2-dimensional array (50x20 matrix)

    return 0;
}

You can try to do it this way (first read the file contents into a string , then convert each char to an int , btw you should use a vector<int> instead of a raw array):

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    string str;
    string total;
    ifstream a_file("data.txt");

    while (getline(a_file, str))
        total += str;

    vector<int> vec;

    for (int i = 0; i < total.size(); i++)
    {
        char c = total[i];
        int a = c - '0';
        vec.push_back(a);
    }     
}

This approach will not work. According to this question , any built-in integral type is likely to be too small to represent the value of a number with 50 decimal digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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