Answer the question
In order to leave comments, you need to log in
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
SS
SS
SS
SS
SS
#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
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
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 questionAsk a Question
731 491 924 answers to any question