7

Is there a way I can read data from a file until a space? I have a file

John J. Doe

and I want to read the file and put John in 1 variable, J. in another variable and Doe in a final variable. How do I do this with ifstream?

Howdy_McGee
  • 10,422
  • 29
  • 111
  • 186

2 Answers2

14

You can just read the values into std::string variables, this will automatically tokenize it.

std::string fName, middleInit, lName;
my_stream >> fName >> middleInit >> lName;
Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
1

Is this your file name or file content? I assume it's file content.

#include<fstream>
#include<string>
//..........
ifstream fin;
fin.open("your file", ifstream::in);
string var1, var2, var3;
fin>> var 1 >> var2 >> var 3;
YankeeWhiskey
  • 1,522
  • 4
  • 20
  • 32
  • This works ifstream file_parse; file_parse.open(file_name, ios::in); string var1, var2, var3; file_parse >> var1 >> var2 >> var3; cout << "var1 " << var1 << endl; cout << "var2 " << var2 << endl; Now I need to have var[] as an array . How ? –  Dec 03 '19 at 23:07
  • int index; ifstream file_parse_array; file_parse_array.open(file_name, ios::in); #define MAX_ARRAY 256 string var[MAX_ARRAY]; // for (index = 1; index < MAX_ARRAY; index++) { file_parse_array >> var[index]; // if (var[index].empty()) continue; cout << "var[index] " << var[index] << endl; } –  Dec 03 '19 at 23:31