Very simply reading in data :-) ......then into a vector

Pages: 12
Hi,

I have some coding experience but am relatively new to c++. I am quite simply trying to read in some numbers I have in a .txt file. They are in a column in the file (sepereated by an "Enter"), does that make any difference? I had a go at writing a program and it compiles but gives me nothing. I'm just wondering if someone might be able to point me in the right direction. Thanks in advance! :-)

Here is a copy of my code;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include<fstream>
using namespace std;

int main () {

    ifstream myReadFile;
    myReadFile.open("myfile.txt");
    char output[300];
    if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {

    myReadFile >>output;
    std::cout<<output;
     
           }
        }
        myReadFile.close();
    return 0;
}


I would ideally like to be able to select a particular line in the .txt file then manipulate the value and output it to a new file. If anyone could help with that bit too it would be amazing also.

Cheers!
:-)
Last edited on
Looks OK try:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <cerrno>

using namespace std;

int main () {

   ifstream myReadFile;
   myReadFile.open("myfile.txt");
   char output[300];
   if (myReadFile.is_open()) {
      while (!myReadFile.eof()) {
         myReadFile >>output;
         cout<<output;
      }
      myReadFile.close();
   }
   else {
     cout << "Error on file open: " << strerror(errno) << endl;
   }
   return 0;
}

to see what the error is if any on the open.

That works good, is there a way where you could just read one line in the file or five lines or as many lines you want to read.
Thank you
renny

Thanks for the code. Unfortunately all it gave me was;



error: 'strerror' was not declared in this scope.



Does that mean I don't have the library for 'strerror' installed?

Also I am expecting the program to print the contents of the .txt file in the terminal. Is that what I should be expecting? I know these are quite fundamental questions but hitting bit of a brick wall here :-)
Last edited on
 
Does that mean I don't have the library for 'strerror' installed? 

Are you on Windows are Linux?
Did you include the cerrno?
You don't have to use that function, you could just print out that you had an error.
 
Is that what I should be expecting? 

Yes, but it will be all of the words concatenated into one line to the terminal.
 
s there a way where you could just read one line in the file or five lines or as many lines you want to read.

Yes, use a for loop in place of the while loop and use the function getline
http://www.cplusplus.com/reference/string/getline/
or
http://www.cplusplus.com/reference/iostream/istream/getline/
At the bottom of each of theses pages are example code to see how to use.
Last edited on

I'm using Linux and when I included cerrno, that was the error that it gave me. Otherwise there doesnt appear to be any error. When it complies and I run the program it just returns me to the command prompt. I've checked the .txt file and it definitely contains data.
When it doesn't work put some print statements to see what is going on and remove the strerror.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#include <iostream>
#include <fstream>

using namespace std;

int main () {

   ifstream myReadFile;
   myReadFile.open("myfile.txt");
   char output[300];
   if (myReadFile.is_open()) {
      cout << "The file is open" << endl;
      while (!myReadFile.eof()) {
         cout << "Reading" << endl;
         myReadFile >>output;
         cout<<output;
      }
      myReadFile.close();
   }
   else {
     cout << "Error on file open" << endl;
   }
   return 0;
}

Yes, I forget about using these print statements throughout the code. Something I used to use all the time to tell where a problem might be.

Thanks for your help! I found it! Was as simple as myfile.txt didn't have the .txt extension.

Stupid me :-) Thanks again!

I'm now wondering how to get that data that is contained in "output" into an array so I don't need to keep opening up files which is slowing my program down quite a lot.

Basically what I would like to do it turn the .txt file into an array.

I'm sure this is easy, just currently trawling the internet for a way to do it that is like mine. Any help? :-)
Since you do not know beforehand how many numbers would be in the file, use a std::vector<> instead of an array. http://www.mochima.com/tutorials/vectors.html

While performing stream input, avoid this kind of construct; it checks for failure to read just before an attempted input (instead of just after)
1
2
3
4
5
while( !myReadFile.eof() ) 
{
    myReadFile  >>  output ; // what happens if this attempt to read fails?
    std::cout <<  output ;
}


Instead, this is idiomatic:
1
2
3
4
5
while( myReadFile >> output ) // as long as we have successfully read something
{
    // use what we have just read
    std::cout <<  output ;
}


So, to read all the integers in the file into a std::vector<int>, we could do something like:
1
2
3
4
5
6
7
8
9
10
std::vector<int> read_from_file( const char* file_path )
{
    std::ifstream file(file_path) ;
    std::vector<int> numbers ;

    int n ;
    while( file >> n ) numbers.push_back(n) ;

    return numbers ;
}


Actually this is idiomatic; but it can wait for now:
1
2
3
4
5
6
std::vector<int> read_from_file( const char* file_path )
{
    std::ifstream file(file_path) ;
    std::istream_iterator<int> begin(file), end ;
    return std::vector<int>( begin, end ) ;
}



Last edited on


Thanks for the code. I like the simplicity of

1
2
3
4
5
 while( myReadFile >> output ) // as long as we have successfully read something
{
    // use what we have just read
    std::cout <<  output ;
}


In fact it feels more intuitive.

I have had a go at implementing the approach you showed using a vector. After including

 
#include <vector> 


Here is what I have done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#include <iostream>
#include <fsteam>
#include <cerrno>
#include <vector>

using namespace std;

std::vector<int> read_from_file( const char* myfile )
{
    std::ifstream file(myfile) ;
    std::vector<int> numbers ;

    int n ;
    while( file >> n ) numbers.push_back(n) ;

    return numbers ;
}

int main () {
{
cout << numbers[0]
}
return 0;
}


At the moment, this is giving me the error;


filename.cpp: In function 'int main()' :
filename.cpp:22: error: 'numbers' was not declared in this scope


I'm guessing that numbers is now an array that contains the data from 'myfile'. How would I go about printing out a specific element in the array?
Last edited on
First off, you're doing some weird things with brackets. But, numbers is not declared in main, it's only in your read_from_file() function, which is also never even used. Your program always starts at main(), so you need to have a function call in there somewhere.

You print out specific elements just how you're doing it. Numbers[0] prints out the first element, the number in te brackets is the index of the element you want, starting at 0.

Ok I could have done without a set of brackets.

Here is what I have now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <fsteam>
#include <cerrno>
#include <vector>

using namespace std;

std::vector<int> read_from_file( const char* myfile )
{
    std::ifstream file(myfile) ;
    std::vector<int> numbers ;

    int n ;
    while( file >> n ) numbers.push_back(n) ;

    return numbers ;
}

int main () 
{
vector printnumbers;
printnumbers = read_from_file;
cout << printnumbers[0];

return 0;
}


As I understand it I am now creating a vector called 'printnumbers' in main which I then populate with the data from the 'read_from_file' function and then print. I accept my previous attempt was pretty much completely stupid but where am I going wrong with this? :-s
printnumbers = read_from_file();
Forgot the parentheses. Compiler is gonna think you're referring to a variable if you forget that. And you have a parameter to worry about.

Have you even tried to compile this?

vector printnumbers;
As far as I know, this won't work. Vector is not a data type.

vector<type> name; Should be the way to declare a vector.

Thanks for the pointers.

I have included the corrections you stated and yea, I have tried to compile it. I am currently getting the error:


filename.cpp: In function 'int main()':
filename.cpp:9: error: too few arguments to function 'std::vector<int, std::allocator<int> > read_from_file(const char*)'
filename.cpp:23:error: at this point in file


I'm guessing these two errors are both part of the same problem. I'll have a look around the net to see if I can find any answers.
Sounds like you didn't pass your function any arguments. It's expecting one.

Here is my complete code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <fstream>
#include <cerrno>
#include <vector>

using namespace std;

std::vector<int> read_from_file(const char* myfile)
{
std::ifstream file(myfile);
std::vector<int> numbers;

int n;
while( file >> n ) numbers.push_back(n) ;

return numbers;
}

int main ()
{
vector<int> printnumbers;
printnumbers = read_from_file();
cout << printnumbers[0]

return 0;
}


I just want to open 'myfile', what more of an argument than 'const char* myfile' does the function need? :-)

With your current implementation, I see no need to even have parameters. This would fix your problem.

It compiles when I have no parameters in the function and loose the ; at the end of line 8 then put "" and .txt on the 'myfile' in line 10 like this;

1
2
3
std::vector<int> read_from_file ()
{
std::ifstream file("myfile.txt");


Only now, once it had successfully compiled and I run it, I only get the command line back. I have checked and the .txt file definitely contains data.
Last edited on

I now have the code compiling but whenever I run the program I get a different integer that bares no resemblance to what is in the .txt file. eg:


3548992

6022976

2537280


The number clearly should not be changing each time I run the program as it should be displaying the value of the first element in the vector. I have had this problem before when writing code in another language but was so long ago and now I can't remember what the problem was. Here is a copy of my code if you want to have a look.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <fstream>
#include <cerrno>
#include <vector>

using namespace std;

std::vector<int> read_from_file()
{
std::ifstream file("myfile.txt");
std::vector<int> numbers;

int n;
while( file >> n ) numbers.push_back(n) ;

return numbers;
}

int main ()
{
vector<int> printnumbers;
printnumbers = read_from_file();
cout << printnumbers[0] << "\n" ;

return 0;
}
Pages: 12