Jump to content
tiodr

Citire din fisiere C++

Recommended Posts

Salut baieti:)

Am si eu o problema. Nu stiu cum sa citesc din fisiere in C++ daca cifrele care trebuie atribuite unui array sunt despartite de un caracter, ex:

6*4*2*2*0*3*5*9*5

sau daca cifrele / numerele sunt puse pe alt rand, ex:


141782417844
142890741890
584375486655
980134980153

Imi puteti posta si mie codurile pentru cele doua exemple ?

Va multumesc frumos!

Edited by tiodr
Link to comment
Share on other sites

daca citesc normal pentru exemplul cu caractere intre cifre imi ia totul puna la primul caracter strain , in cazul acesta * si daca citesc direct pentru exemplul cu numerele despartite pe mai multe linii imi ia doar prima linie din fisier

Link to comment
Share on other sites

C like

#include <cstdio>
#include <cstdlib>
#include <cctype>

typedef short unsigned int sui;

int main()
{
char fname[64], chr;
unsigned long i, cnt = 0;
sui* buffer = 0;
printf("Enter file path/name: ");
scanf("%s", fname);
FILE* fin = fopen(fname, "rt");
while (!feof(fin)) {
chr = fgetc(fin);
if (isdigit(chr)) {
buffer = (sui*) realloc(buffer, (cnt + 1) * sizeof(sui));
buffer[cnt++] = chr - '0';
}
}
fclose(fin);
for (i = 0; i < cnt; i++) {
printf("%u", buffer[i]);
}
free(buffer);
return 0;
}

or C++

#include <iostream>
#include <fstream>
#define n 64
using namespace std;

void compute(char* buffer)
{
char c;
unsigned long rh, wh;
rh = wh = 0;
while ((c = buffer[rh++])) {
if (c >= '0' && c <= '9') {
buffer[wh++] = c;
}
}
buffer[wh] = 0;
}

int main()
{
char fname[n], * buffer;
long unsigned size;
fstream myfile;
cout << "Enter file path/name: ";
cin.getline(fname, n);
myfile.open(fname, ios::in | ios::binary | ios::ate);
size = (long unsigned) myfile.tellg();
buffer = new char[size + 1];
myfile.seekg(0, ios::beg);
myfile.read(buffer, size);
myfile.close();
buffer[size] = 0;
compute(buffer);
cout << buffer;
delete[] buffer;
return 0;
}

In al doilea exemplu l-am lasat de tip char nu l-am mai facut int/short ca sa-l afiseze direct dar de acolo te descurci nu-i problema.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...