Hello,
It's been a while since I programmed, and I've gotten rusty on some of the main points. I've made a simple example to try to refresh my memory.
Basically, I have the source files attached below. They are the actual implementation of some csv functions, the corresponding header, and a main program trying to use them. I'm trying to compile main.cpp to use the code from krs_csv.cpp with the following g++ call:
g++ main.cpp krs_csv.cpp
However, I keep getting the following error messages:
Code:
krs_csv.cpp:1:1: error: ‘string’ in namespace ‘std’ does not name a type
krs_csv.cpp:13:1: error: ‘string’ in namespace ‘std’ does not name a type
The source files are below:
main.cpp
Code:
#include<iostream>
#include<string>
#include "krs_csv.h"
int main( int argc, char ** argv){
int n=1;
std::string buf;
std::fstream file;
file.open( "data.csv", std::ios::in );
buf = get_nth_line( file, 4 );
buf = get_nth_entry(buf, 0, " ");
std::cout<<"2nd entry of 2nd line is: "<<buf<<"\n";
return 0;
}
krs_csv.cpp
Code:
#include "krs_csv.h"
std::string get_nth_line( std::fstream & file, int n){
std::string buffer;
file.seekg( 0, std::ios::beg );
for( int i=0; i < n ; i++)
getline( file, buffer, '\n' );
return buffer;
}
std::string get_nth_entry( std::string line, int n , std::string sep){
int l=-1;
int r=0;
//find preceding occurrence of sep
for( int i=0; i < (n-1); i++)
l = line.find( sep, l+1 );
r = line.find( sep, l+1);
if( r == -1){
return line.substr( l+1, std::string::npos);
}
else{
return line.substr( l+1, r-l-1 );
}
}
krs_csv.h
Code:
#ifndef _STRING_INCLUDED
#define _STRING_INCLUDED
#include<string>
#endif
#ifndef _FSTREAM_INCLUDED
#define _FSTREAM_INCLUDED
#include<fstream>
#endif
#ifndef _FUNC_H
#define _FUNC_H
std::string get_nth_line( std::fstream & file, int n);
std::string get_nth_entry( std::string line, int n , std::string sep);
#endif /*_FUNC_H */
Can you please critique this "way" of using the #include command and the way I've organized the files? Is there a smarter way to do something like this?
I understand this is contrived, and there is error-checking and other things that should be added to the code, I'm just wondering if I've roughly set up the source files and include dependencies okay.