-1

I want to read from a file only the variables that matter, for example I have a contacts.txt and it says something like:

Name Penelope Pasaft
Cel 1535363236

and the only things I want to read or save at memory at specific variables for example the variable name and cel are the data that really matters.

In this case, I want to save Penelope Pasaft to the variable name and the specific number given to the variable cel.

In C, I used to use something like scanf("Name %s",name) but in C++, I don't know if there is something like that or how to do it!

Praveen Vinny
  • 2,372
  • 6
  • 32
  • 40
Arya
  • 1
  • 1

1 Answers1

0

Let us consider your contacts.txt is as follows:

Name Penelope Pasaft
Cel 1535363236
Name David Beckam
Cel 6354562234

Then, the following code will produce the output:

#include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
#include <cstdlib>


using namespace std;

int main() {
ifstream readFromFile("contacts.txt");

string name;
string Cel;
string line;
int count = 0;
if (readFromFile.is_open()) {
    while(!readFromFile.eof()) {
    (count==2)?count=0:count=count;
        getline(readFromFile, line, ' ');
            if(line == "Name") {
            getline(readFromFile, name, '\n');
            ++ count;
            } else if(line == "Cel") {
                getline(readFromFile, Cel, '\n');
            count ++;
            }

    if(count==2) {
        cout<<"Name: "<<name<<endl;
        cout<<"Cel: "<<Cel<<endl;
        }
    }
}

return 0;
}

Output will be as follows:

$ g++ test.cpp 
$ ./a.out
Name: Penelope Pasaft
Cel: 1535363236
Name: David Beckam
Cel: 6354562234
Praveen Vinny
  • 2,372
  • 6
  • 32
  • 40
  • @Arya - Please try as mentioned in the whole code and please accept the answer if it is working. – Praveen Vinny Sep 07 '16 at 04:32
  • You should not loop using `eof()`: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Galik Sep 07 '16 at 05:40