简体   繁体   中英

reading from a text file to array in c++?

I am trying to to read each line from a text file and put in array column ,I really tried this :

    string buffer[256];
string a;
ifstream myfile ("1.txt");

for(i=0;i<10000;i++)
    {

        //readArrivalTimes(i);
        myfile.getline (buffer,100);
        a[i]=buffer;
    }

but It is not working

so I did try for one of the solutions you gave me guys and I did it like this :

std::vector<std::string> v;
std::string buffer;


string a[1024];
ifstream myfile;
myfile.open("1.txt");

for(i=0;i<n;i++)
{
    getline (myfile, buffer);

    a[i]= buffer;
    cout << buffer << "\n";
}

but as we can see it's string !

can we make it works as integer?

[Solved :)]

first of all thanks for everybody help me with this, I really appreciate your help, I am a totally new to c++.

and for sure it's not a homework.

I did some modifications to the code so it can works with integers

int a[1024];
ifstream myfile;
myfile.open("1.txt");

for(i=0;i<n;i++)
{
    getline (myfile, buffer);

    a[i]= atoi(buffer.c_str());
    cout << buffer << "\n";
}

thank you very much.

There are many mistakes in your code.
Some are already mentioned, as assigning the char* to the int array.

But your approach is more C than C++. In C++ it would look more like this:

std::vector<std::string> lines;
std::ifstream myfile("1.txt");
if(myfile.isopen())
{
    std::string line;
    while(getline(myfile, line))
    {
        lines.push_back(line);
    }
}

I haven't tested it, but it should show you a way how to do this.

Edit: Changed the code according to comments.

Edit again to make it work with integers:

std::vector<int> numbers;
std::ifstream myfile("1.txt");
if(myfile.isopen())
{
    std::string line;
    while(getline(myfile, line))
    {
        int number;
        std::istringstream(line) >> number;
        numbers.push_back(number);
    }
}

a is a string, which is an abstraction for a collection of characters.

a[i] will return a reference to an individual character.

buffer is an array of characters. The C/C++ convention in that the name of the array names a pointer to its first element.

So, what you are doing in your loop is assigning the ith element of a to the address of the beginning of your buffer, which is almost certainly not what you want to do.

Likely what you want to do is make a an array of strings; ie replace

string a;

with

string a[10000];

There's other things to address in your code; for example, what if your file has < 10k lines?

    int a[1024];
ifstream myfile;
myfile.open("1.txt");
for(i=0;i<n;i++)
{
    getline (myfile, buffer);

    a[i]= atoi(buffer.c_str());
    cout << buffer << "\n";
}

this is the right answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM