c++ - Input only integers from a line of a .txt file -


this question has answer here:

i wondering there way of getting integers line of text using c++ without using seekg().

lets file data.txt has line: position {324,71,32} in it, , want integer values.

i tried following code didn't work, , i've searched web solution , didn't find - that's why i'm asking.

#include <iostream> #include <fstream>  using namespace std;  int main() {     string x, num1, num2, num3;     fstream fs;     fs.open("data.txt", ios::in);     if (fs.fail())         cerr << "failed open file";     fs >> x;     num1 = x;     fs >> x;     num2 = x;     fs >> x;     num3 = x;     cout << num1 << " " << num2 << " " <<num3 << endl;     return 0; }     

try more this:

#include <iostream> #include <fstream>  using namespace std;  int main() {     string x;     char c;     int num1, num2, num3;      fstream fs;     fs.open("data.txt", ios::in);     if (!fs)         cerr << "failed open file";     else     {         fs >> x; // "position"         fs >> c; // '{'          fs >> num1;         fs >> c; // ','           fs >> num2;         fs >> c; // ','         fs >> num3;          if (!fs)             cerr << "failed read file";         else             cout << num1 << " " << num2 << " " << num3 << endl;     }     return 0; }     

or this:

#include <iostream> #include <fstream> #include <sstream>  using namespace std;  int main() {     string s, x;     char c;     int num1, num2, num3;      fstream fs;     fs.open("data.txt", ios::in);     if (!fs)         cerr << "failed open file";     else if (!getline(fs, s))         cerr << "failed read file";     else     {         istringstream iss(s);          iss >> x; // "position"         iss >> c; // '{'          iss >> num1;         iss >> c; // ','           iss >> num2;         iss >> c; // ','         iss >> num3;          if (!iss)             cerr << "failed parse line";         else             cout << num1 << " " << num2 << " " << num3 << endl;     }     return 0; }     

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -