logo
Tags down

shadow

c++ program not printing 2d vector grid properly but is close


By : user2174260
Date : October 18 2020, 08:10 PM
will help you Im currently trying to parse a text file of numbers into a 2d vector that will be modified later, but with my code so far. I'm getting this: , One quick fix gets rid of most of your problem:
code :
int main()
{
//parsing the textfile.
    vector<vector<char>> grid;
    fstream fin;
    char ch;

    // Hardcoded value. Typing the same thing in over and over while debugging is for suckers.
    string name("data.txt"); //File Name. 
// 2D Vector.
    vector<char> temp;
// Temporary vector to be pushed
// into vec, since its a vector of vectors.
    fin.open(name.c_str(), ios::in);
// Assume name as an arbitary file.
    while (fin.get(ch)) // the change: Slightly different get and getting in the loop
                        // condition. If nothing is gotten the loop doesn't enter
                        // solves almost all of the problems.
    {
        if (ch != '\n')
        {
            temp.push_back(ch);
            cout << ch;
        }
        else
        {
            grid.push_back(temp);
            temp.clear();
            cout << ch; 
        }
    }
    for (int i = 0; i < grid.size(); i++)
    {
        for (int j = 0; j < grid[i].size(); j++)
        {
            cout << grid[i][j];
        }
    }
}
845630179
032918654
190745328
683074912
457201836
219863540
361429705
074186093
920357461845630179032918654190745328683074912457201836219863540361429705074186093
845630179
032918654
190745328
683074912
457201836
219863540
361429705
074186093
920357461
845630179032918654190745328683074912457201836219863540361429705074186093
int main()
{
//parsing the textfile.
    vector<vector<char>> grid;
    fstream fin;
    char ch;
    string name("data.txt"); //File Name.
// 2D Vector.
    vector<char> temp;
// Temporary vector to be pushed
// into vec, since its a vector of vectors.
    fin.open(name.c_str(), ios::in);
// Assume name as an arbitary file.
    while (fin.get(ch))
    {
        if (ch != '\n')
        {
            temp.push_back(ch);
        }
        else
        {
            grid.push_back(temp);
            temp.clear();
        }
    }
    for (int i = 0; i < grid.size(); i++)
    {
        for (int j = 0; j < grid[i].size(); j++)
        {
            cout << grid[i][j];
        }
        cout << '\n'; // 
    }
}
 int main()
{
//parsing the textfile.
    vector<string> grid;
    fstream fin;
// 2D Vector.
    vector<char> temp;
// Temporary vector to be pushed
// into vec, since its a vector of vectors.
    fin.open("data.txt", ios::in);
// Assume name as an arbitary file.
    string line;
    while (getline (fin, line))
    {
        grid.push_back(line);
        temp.clear();
    }
    for (int i = 0; i < grid.size(); i++)
    {
        for (int j = 0; j < grid[i].size(); j++)
        {
            cout << grid[i][j];
        }
        cout << '\n'; // getline ate the newline. Have to put it back
    }
}


Share : facebook icon twitter icon

Print an error message without printing a traceback and close the program when a condition is not met


By : At Newsexpress
Date : March 29 2020, 07:55 AM

Vector memory on Program close c++


By : Tamanesh Kauri
Date : March 29 2020, 07:55 AM
Does that help This depends on how you declared your vector.
If you use RAII (your vector is a stack object, std::vector<...> myVec;) Or if you created it on the heap (std::vector<...>* myVec = new std::vector<...>();)

Program crashes at printing string vector


By : stackflow_x
Date : March 29 2020, 07:55 AM
hope this fix your issue I'm making a program that write and read "reminders", and i when i'll print a string vector with the "reminders" it crashes and i don't know why this happens, it can compile, but it crashes at running, thanks for anyone that tried to help. Here's the code: , This is a problem:
code :
LPSTR buffer;
GetCurrentDirectory(MAX_PATH, buffer);
char buffer[MAX_PATH+1];   // or TCHAR
GetCurrentDirectory(sizeof buffer, buffer);

Why is my C program not counting and printing integers from a text file properly?


By : user2023583
Date : March 29 2020, 07:55 AM
this one helps.
The output cuts off certain numbers and its giving me the incorrect total number of integers.
code :
while(getc(fp) != EOF)
    ...
fgets(str, 200, fp);
long int strtol(const char *nptr, char **endptr, int base);
#include <stdio.h>
#include <stdlib.h>     /* for strtol */
#include <string.h>     /* for strncpy */
#include <errno.h>      /* for errno */

#define MAXC 1024   /* constant - max chars in line */

int main (void) {

    char str[MAXC] = "";    /* str to hold line, initialized all zero */

    while (fgets (str, MAXC, stdin)) {  /* read each line of input */
        char *p = str,      /* pointer for strtol */
            *endptr = NULL; /* end pointer for strtol */

        while (*p) {    /* work down str parsing integer or hex values */
            long val = strtol (p, &endptr, 0);  /* convert from p */

            /* validate conversion */
            if (p != endptr) {  /* were digits converted? */
                if (!errno) {   /* if errno 0, successful conversion */
                    char ascii[MAXC] = "";  /* for string converted */

                    strncpy (ascii, p, endptr - p); /* copy to ascii */
                    ascii[endptr-p] = 0;    /* nul-terminate ascii */

                    /* test whether string begins "0x" or "0X", output */
                    if (*p == '0' && (*(p + 1) == 'x' || *(p + 1) == 'X'))
                        printf ("hex conversion:  %-10s %10lu  0x%lx\n",
                                ascii, val, val);
                    else
                        printf ("int conversion:  %-10s % ld\n",
                                ascii, val);
                }
                p = endptr; /* advance p to 1-past end of converted string */
            }

            /* find start of next valid number in str, including (+/-) */
            for (; *p; p++) {
                if ('0' <= *p && *p <= '9')  /* positive value */
                    break;          /* explicitly signed value */
                if ((*p == '+' || *p == '-') && '0' <= *(p+1) && *(p+1) <= '9')
                    break;
            }
        }
    }

    return 0;
}
$ ./bin/fgets_strtol_any <debug/dat/integermess.txt
int conversion:  123         123
int conversion:  34          34
int conversion:  -54        -54
int conversion:  21          21
int conversion:  45          45
int conversion:  34          34
int conversion:  -54        -54
int conversion:  21          21
...
int conversion:  48          48
int conversion:  29          29
int conversion:  39          39
int conversion:  40          40
int conversion:  29          29
#include <stdio.h>
#include <stdlib.h>

#define MAXC 1024

int main (int argc, char **argv) {

    char buf[MAXC] = "";    /* buffer to hold MAXC chars at a time */
    int nval = 0;           /* total number of integers found */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while (fgets (buf, MAXC, fp)) {

        char *p = buf;      /* pointer to line */
        int val,            /* int val parsed */
            nchars = 0;     /* number of chars read */

        /* while chars remain in buf and a valid conversion to int takes place
         * output the integer found and update p to point to the start of the
         * next digit.
         */
        while (*p) {
            if (sscanf (p, "%d%n", &val, &nchars) == 1) {
                printf (" %d", val);
                if (++nval % 10 == 0)     /* output 10 int per line */
                    putchar ('\n');
            }
            p += nchars;        /* move p nchars forward in buf */

            /* find next number in buf */
            for (; *p; p++) {
                if (*p >= '0' && *p <= '9') /* positive value */
                    break;
                if (*p == '-' && *(p+1) >= '0' && *(p+1) <= '9') /* negative */
                    break;
            }
        }
    }
    printf ("\n %d integers found.\n", nval);

    if (fp != stdin) fclose (fp);     /* close file if not stdin */

    return 0;
}
$ ./bin/fgets_sscanf_int_any_ex <debug/dat/integermess.txt
 123 34 -54 21 45 34 65 -54 21 45
 34 65 -34 24 58 49 45 10 -57 20
 57 39 20 58 23 10 20 58 -60 76
 -82 28 28 -37 49 358 47 -50 37 29
 57 -29 -20 47 69 93 57 23 49 -38
 49 27 -40 48 39 56 -30 47 28 49
 37 49 27 26 10 20 58 -60 26 10
 20 58 -60 76 -82 28 28 -37 49 -28
 93 28 73 47 27 83 37 -29 40 37
 49 20 17 -26 12 17 17 18 38 29
 39 -118 19 10 20 58 -60 76 -82 28
 28 -37 49 59 10 58 -60 76 -82 28
 28 -37 49 59 10 20 58 -60 76 -82
 28 28 -37 49 30 -58 58 38 49 30
 -58 58 38 49 30 -58 58 38 28 39
 39 48 23 -50 28 48 29 39 40 29

 160 integers found.

why doesnt't my turtle program close properly?


By : themapguy
Date : March 29 2020, 07:55 AM
Any of those help (As posted, your code doesn't start up correctly for me.)
My concern would be you have both a mainloop() and an exitonclick(). These perform the same function (exitonclick() sets the onclick() to bye() and calls mainloop()) and there should only be one of them. (Ditto done().)
code :
from turtle import Screen, Turtle
from datetime import datetime

FONT = ("Courier", 11, "bold")

def jump(distanz, winkel=0):
    turtle.penup()
    turtle.right(winkel)
    turtle.forward(distanz)
    turtle.left(winkel)
    turtle.pendown()

def hand(laenge, spitze):
    turtle.fd(laenge * 1.15)
    turtle.rt(90)
    turtle.fd(spitze / 2.0)
    turtle.lt(120)
    turtle.fd(spitze)
    turtle.lt(120)
    turtle.fd(spitze)
    turtle.lt(120)
    turtle.fd(spitze / 2.0)

def make_hand_shape(name, laenge, spitze):
    turtle.reset()
    turtle.hideturtle()
    jump(-laenge * 0.15)
    turtle.begin_poly()
    hand(laenge, spitze)
    turtle.end_poly()
    hand_form = turtle.get_poly()
    screen.register_shape(name, hand_form)

def clockface(radius):
    turtle.reset()
    turtle.hideturtle()
    turtle.pensize(7)

    for i in range(60):
        jump(radius)
        if i % 5 == 0:
            turtle.fd(5)
            turtle.penup()
            turtle.fd(20)
            turtle.pendown()
            jump(-radius - 25)
        else:
            turtle.dot(3)
            jump(-radius)

        turtle.rt(6)


def wochentag(t):
    wochentag = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

    return wochentag[t.weekday()]

def datum(z):
    monat = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "June", "July", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."]

    j = z.year
    m = monat[z.month - 1]
    t = z.day

    return "%s %d %d" % (m, t, j)

def prepare_to_stop(x, y):
    global running

    running = False

def tick():
    t = datetime.today()

    sekunde = t.second + t.microsecond * 0.000001
    minute = t.minute + sekunde / 60.0
    stunde = t.hour + minute / 60.0

    screen.tracer(False)

    wochentag_writer.clear()
    wochentag_writer.write(wochentag(t), align="center", font=FONT)

    datum_writer.clear()
    datum_writer.write(datum(t), align="center", font=FONT)

    screen.tracer(True)

    second_hand.setheading(6 * sekunde)
    minute_hand.setheading(6 * minute)
    hour_hand.setheading(30 * stunde)

    if running:
        screen.ontimer(tick, 100)
    else:
        screen.bye()

screen = Screen()
screen.setup(width=170, height=170)
screen.mode("logo")
screen.title("Clock")

turtle = Turtle(visible=False)

screen.tracer(False)

make_hand_shape("second_hand", 60, 15)
make_hand_shape("minute_hand", 50, 15)
make_hand_shape("hour_hand", 30, 15)

clockface(60)

second_hand = Turtle()
second_hand.shape("second_hand")
second_hand.color("gray20", "gray80")

minute_hand = Turtle()
minute_hand.shape("minute_hand")
minute_hand.color("blue1", "red1")

hour_hand = Turtle()
hour_hand.shape("hour_hand")
hour_hand.color("blue3", "red3")

for hand in second_hand, minute_hand, hour_hand:
    hand.shapesize(1, 1, 3)
    hand.speed('fastest')

wochentag_writer = Turtle(visible=False)
wochentag_writer.penup()
wochentag_writer.forward(25)
wochentag_writer.write("", align="center", font=FONT)

datum_writer = Turtle(visible=False)
datum_writer.penup()
datum_writer.back(35)
datum_writer.write("", align="center", font=FONT)

screen.tracer(True)

screen.screensize(50, 50)

canvas = screen.getcanvas()
canvas._root().overrideredirect(True)
rootwindow = canvas.winfo_toplevel()
rootwindow.call('wm', 'attributes', '.', '-topmost', '1')

running = True

tick()
screen.onclick(prepare_to_stop)
screen.mainloop()
Related Posts Related Posts :
  • Why am I getting Error Cannot find source file in cmake?
  • Good practice on porting C++ code from GCC to MSVC?
  • How to return C pointer automatically
  • create a Dynamic std::array of std::array
  • How to avoid recursion in native visualisers?
  • C++: avoid automatic conversion of string to bool in overloads
  • Can't get dlib rectangle coords from mmod face detector
  • c++: OpenCV cv::Mat::at cannot assign to a variable that is const
  • PrintWindow and BitBlt of hidden windows
  • Why is the default value of a function 1?
  • Intercept any outgoing network request in V8 ( at core level )
  • Process memory reading always returns 0
  • OOP: When should I declare class members dynamically?
  • How set QLabel in a corner of Windows even when i do resize in QT?
  • Explanation of the output of this program:
  • Delete and upload all .bmp files in folder and load DLL Library
  • qmltestcase can't find c++ class method
  • Getting sensor data on Windows 10 without UWP
  • Read a sequence of positive numbers and print their binary representation
  • Template function broken after compiling with C++11
  • Is there a data race on packaged task arguments?
  • Malloc of pointer to an array- C++
  • Changing audio stream from physical input
  • Sorting a Vector of a custom class with std::sort() causes a segmentation fault
  • fastest way to read the last line of a string?
  • std::num_put issue with nan-boxing due to auto-cast from float to double
  • Difficulty with map's find function
  • Visual C++ executable will not run without Boost DLLs
  • #include <mutex> causes the bind() function call to throw errors at compile time, why?
  • Random_shuffle alternative in C++Builder6
  • C++ unique_ptr initialization
  • Is it really safe not to check in the copy assignemt operator whether an object is assigned to itself?
  • How to avoid passing param to template instantiation of reference-based helper class
  • Why isn't my array incrementing properly?
  • How to create your own Function for Async operation in c++ UWP?
  • C++ accessing a variable in a union struct
  • What does a implicitly defined destructor do
  • Member was not declared in base class template
  • Overloading << sign follow by a boolean expression
  • looser throw specifier for virtual function : GCC 4.9 complains but MSVC
  • Why does decltype(auto) not work as expected?
  • How to print and read at in the same line in Haskell?
  • SFINAE with Templated class Member functions
  • how to declare char * with input of {"data": "0001"}'
  • c++ program compile with LAPACK library
  • Enum in C++ Classes
  • Sort Specific Column of 2D int array (C++)
  • Unordered_map find const wchar_t*
  • OK to use these two parameters each independently, but fail to have both
  • Two classes with same, standalone, hidden functionality
  • C++: Instantiate object with no namespace
  • qml set text property from c++
  • Confused Backtrace of GDB while analysing core dump file at ../stdlib/strtod_l.c:734
  • syscall.MustLoadDll.MustFindProc throws "The specified procedure could not be found"
  • Why does structured binding not work as expected on struct?
  • Using lambda expression as Compare for std::set, when it's inside a vector
  • C++ Can't reference key of the map
  • Generic QuickSort implemented with vector and iterators C++
  • purpose for wait_for function in condition variable - C++11
  • Can I fill a template parameter with a nested class in this class?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org