P
P
parkito2015-09-07 23:18:25
C++ / C#
parkito, 2015-09-07 23:18:25

How to count strings into an array?

Hello. Please help me solve the following problem:
The program should read lines into a character array from a file.
The in.txt file is the following

AA
BB
CC
DD

The program I wrote is not working correctly. Instead of putting lines from the file into an array, it is filled with only the last line. those.
SS
SS
SS
SS
SS

In the process of debugging, I noticed something that simply struck me. The line is read normally, entered into the array, the next line is read, and then the previous and next elements of the array are filled with new ones. And so it turns out that the last line is duplicated for the entire array. Tell me what is my jamb?
Program code
#include "stdlib.h"
#include "string.h"
#include <iostream>
#include <fstream>
using namespace std;
int main() {
    setlocale(LC_ALL, "Rus");
    const int DAYS = 5;
    char *array[DAYS];
    ifstream in;
    in.open("in.txt");
    if (in.fail()) {
        cout << "Ошибка. Файл не найден! ";
        cin.get();
        cin.get();
        exit(0);
    }

    char *str;
    for (int i = 0; i < 5 ; i++) {
        in>>str;
        array[i]=str;
         }
     in.close();
    for (int i = 0; i <5 ; ++i) {
        cout<<array[i]<<endl;

    }
    cin.get();
    cin.get();
    return 0;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2015-09-07
@parkito

Reading into an unallocated buffer ( char *str;). Well, the program doesn't crash. Memory for the line must be allocated.
Since you have C++ here, it's easiest to learn how to use std::string

S
slinkinone, 2015-09-07
@slinkinone

You need to allocate memory under str before reading ...
Imagine that you have a variable of type pointer, but to start writing to this pointer, you need to allocate memory ... And with <<, the program tries to transfer everything from in to the area pointed to by str ... But since nothing is allocated under str, the program writes to an area that is probably not intended for writing and can corrupt the heap data ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question