-1

I have managed to write some code that can read from a .txt file, however I want my program to only read in important data.

For example, if my text file had the following data:

Name= Samuel
Favourite colour= Green
Age= 24
Gender= Male

I want my program to just read, and ignore everything before the "="

Samuel
Green
24
Male

I looked into the .substr() method, however, you need to know the exact position of the = sign.

This is my code, and it does not work

while ( getline (open_file,line) ){
  for (int i=0; i<line.length(); i++){
    if (line == "="){
      cout << " " + (rest of the line;
    }

I would really appreciate it if someone could help me out.

user4167396
  • 29
  • 1
  • 7
  • 1
    so why not find the location of the `=`? e.g. strstr()? – Marc B Oct 22 '14 at 20:42
  • @MarcB because the = is in a different position in every line and when the user opens the file the program does not know where it is. The = sign won't be in the same position every time – user4167396 Oct 22 '14 at 21:13
  • which is exactly what those functions are for. "find a substring in a string". search for the `=`, gets its location, then use that for your substring extraction. – Marc B Oct 22 '14 at 21:21
  • @MarcB: The OP could also use the `std::string::find('=')` method, which will return the position of the `=` or `std::string::npos` if the '=' is not found. – Thomas Matthews Oct 22 '14 at 23:33

1 Answers1

0

The most efficient way to read in data files is to read in a line at a time into a string variable. Next, extract the important parts.

Your data file looks like it is of the format:

<name> = <value>

I suggest you extract both name and value as strings (e.g. substrings), then you can pass the original data, in its original form, to other functions. Let the other functions worry about converting into integers or other data types.

The name field can be found by searching for the '=' and remembering the position of the '='. Next use the substring method and extract from the beginning of the string to the position before the '='.

The value is the substring that starts after the position of the '=' to the end of the string.

I'll let you look up the std::string functions and how to use them. I don't want to give you the code because you won't learn as much (such as how to look up functions).

See also std::getline.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154