logo
down
shadow

c++ Read text file and input the numbers into a 2D array


c++ Read text file and input the numbers into a 2D array

Content Index :

c++ Read text file and input the numbers into a 2D array
Tag : cpp , By : RyanMcG
Date : November 25 2020, 07:06 PM


Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to read and add only numbers to array from a text file


Tag : arrays , By : Matt Watson
Date : March 29 2020, 07:55 AM
I wish did fix the issue. All the said three ie; "3, 3-43 and 4-42 are strings
Either u read a string and split it and check for number at " and - or you put in a space between characters and integers. The JVM after compilation would treat it all as string if it cannot be converted to a double. And the File reader wont stop reading till at least a space or a newline. Hence your code would never work the way you intend it to unless you do as I said above.
66.56
" 3
JAVA
3 - 43
5 - 42
2.1
1
public static void main(String[] args) {
        File x = new File(args[0]);
        try {
            Scanner in = new Scanner(new FileInputStream(x));
            ArrayList<Double> test = new ArrayList<>();
            while (in.hasNext()) {
                if (in.hasNextDouble()) {
                    Double f = in.nextDouble();
                    test.add(f);
                } else {
                    String s=in.next();
                    if(s.contains("\"")){
                        String splits[]=s.split("\"");
                        test.add(Double.parseDouble(splits[1]));
                    }
                    else if (s.contains("-")){
                        String splits[]=s.split("-");
                        test.add(Double.parseDouble(splits[0]));
                        test.add(Double.parseDouble(splits[1]));
                    }
                }
            }
            System.out.println(test);
        } catch (IOException e) {
            System.err.println("Exception during reading: " + e);
        }
}

Read numbers from text file and use them as input


Tag : c , By : haver
Date : March 29 2020, 07:55 AM
like below fixes the issue Here is a small code to read character by character and store only the wanted numbers:
C Code:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int c;                     // Character read from the file
    int cpt;                    // Counter (to get only 5 numbers per line)
    int i,j;                     // Array indexes
    int data[4][5];       // 2D integer array to store the data
    FILE *f;                // File

    if ((f = fopen("file.txt", "r")) == NULL)       // Open the file in "read" mode
    {
        printf ("file can't be opened'\n");
        exit(255);
    }

    // Counter and indexes initialization
    cpt=0;
    i=0;
    j=0;

    // Read the file till the EOF (end of file)
    while ((c = fgetc(f)) != EOF)
    {
        // If 5 numbers read, go to new line, first index in the data array and to the next line in the file
        if(cpt==5)
        {
            i++;
            cpt=0;
            j=0;
            while(c != '\n' && c != EOF)
                c=fgetc(f);
        }

        // If a number is read, store it at the right place in the array
        if(c>='0'&&c<='9')
        {
               // Convert character to integer (see ascii table)
            data[i][j] = c-'0';
            j++;
            cpt++;
        }
    }

        // Display the array
    for(i=0;i<4;i++)
    {
        for(j=0;j<5;j++)
            printf("%d ", data[i][j]);
        printf("\n");
    }

    fclose(f);
}
0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1

Read numbers from text file to 2D array


Tag : c , By : NewGirl
Date : March 29 2020, 07:55 AM
With these it helps You were well on your way, you just had problems thinking you were reading a character array instead of an array of signed characters (which could be changed to int, etc) Here is your example:
#include <stdio.h>

#define MAXB 32
#define MAXL 18
#define MAXD 3

int main(void)
{
    int i = 0;
    int numlines = 0;
    char buf[MAXB] = {0};
    char lines[MAXL][MAXD];

    FILE *fp = fopen("inputs/control.txt", "r");

    if (fp == 0)
    {
       fprintf(stderr, "failed to open inputs/control.txt\n");
       return 1;
    }

    while (i < MAXL && fgets (buf, MAXB - 1, fp))
    {
        if (sscanf (buf, "%hhd %hhd %hhd", &lines[i][0], &lines[i][1], &lines[i][2]) == 3)
            i++;
    }

    fclose(fp);

    numlines = i;
    int j = 0;

    for (i = 0; i < numlines; i++)
        for (j = 0; j < MAXD; j++)
            printf (" line[%2d][%2d] : %hhd\n", i, j, lines[i][j]);

    printf ("\n");

    return 0;
}
$ ./bin/read_array_a3
 line[ 0][ 0] : 1
 line[ 0][ 1] : 0
 line[ 0][ 2] : 0
 line[ 1][ 0] : 0
 line[ 1][ 1] : 0
 line[ 1][ 2] : 0
 line[ 2][ 0] : 1
 line[ 2][ 1] : 0
 line[ 2][ 2] : 1
 line[ 3][ 0] : 0
 line[ 3][ 1] : 0
 line[ 3][ 2] : 2
 line[ 4][ 0] : 1
 line[ 4][ 1] : 0
 line[ 4][ 2] : 2

How do I read a text file of numbers into an array of arrays


Tag : python , By : algoRhythm99
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I know it's not pretty and there is probably a MUCH BETTER way to do this, but it works. That being said, if someone could show me a better way, it would be much appreciated.
pointlist = []
f = open(args["slots"])
data = f.read().split()
for row in data:
    tmp = []
    col = row.split(";")
    for points in col:
        xy = points.split(",")
        tmp += [[int(pt) for pt in xy]]
    pointlist += [tmp]

slots = np.asarray(pointlist)

trying to compare user input with a text file and then read the values of numbers from that point on java


Tag : java , By : mux
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Passing a function identifier as an rvalue reference and applying std::move() to it
  • The conditional operator is not allowing the program to terminate
  • Define a c++ string as "\"
  • memcpy on __declspec naked returns unexpected bytes
  • What is the proper way to link enums with CMake?
  • is it safe to use the same mutex with lock_gard and without it in other parts of code
  • How to decode MAP Invoke messages using asn1c generated code
  • How do you write multiple lines in a .txt with recursion?
  • Member function with strange type causing callback function mismatch
  • Visual Studio optimisations break SDL graphical output
  • How to use less memory in Sieve_of_Eratosthenes
  • Covariance in Callback Parameters C++
  • switch may fall through (no it may not)
  • Compilation fails calling Cocoa function from C++
  • How to handle classes with differently named member functions in algorithms?
  • Convert QString to QJsonArray
  • Data exchange finished in CPropertyPage::OnOK?
  • Template member specialization in template class
  • Is it not possible to assign a struct to an index of a vector?
  • Why is empty unordered_map.find not returning end()?
  • Template argument deduction for inheriting specializations
  • dlopen undefined reference
  • Member function of class with template arguments and default arguments outside class
  • Is it possible to implement a non-owning "slightly smart" pointer on top of standard weak pointers?
  • how to configure the AcquireCredentialsHandleA correctly
  • Using private versions of global extern variables with OpenMP
  • Eigen Block wrong amount of columns and rows
  • Memory alignment rules in inheritance
  • Is nullptr falsy?
  • tm_wday returns a large integer outside 0-6 range
  • Scope a using declaration, inside a header
  • How to specify constructor's template arguments inside a new expression?
  • Sort an array via x86 Assembly (embedded in C++)?? Possible?
  • How to Replace only Part of the Variable using #define
  • How do you compare the performace of valarrays vs built-in arrays?
  • Is it normal for C++ static initialization to appear twice in the same backtrace?
  • c++ generate a good random seed for psudo random number generators
  • Why isn't my operator overloading working properly?
  • Getting meaningful error messages from fstream's in C++
  • C++: Converting Julian dates to Gregorian
  • Could someone explain this interesting behaviour with Sleep(1)?
  • Is it possible to roll a significantly faster version of modf
  • Updating pointer using signals and slots
  • How are classes more secure than structures?
  • finding "distance" between two pixel's colors
  • C++ Greatest Number Verification
  • Why does my token return NULL and how can I fix it?(c++)
  • C++ enforce conditions on inherited classes
  • what happened if an exception is not captured?
  • Redundant naming in C/C++ typedefs/structs
  • question about STL thread-safe and STL debugging
  • killing a separate thread having a socket
  • Returning the size of available virtual memory at run-time in C++
  • Parallel computing for integrals
  • How do I force my std::map to deallocate memory used?
  • C++ Templates: implicit conversion, no matching function for call to ctor
  • Adding python script to c++ project
  • C++ private pointer "leaking"?
  • Initializing Primitive Array to One Value
  • how is push_back implemented in STL vector?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com