2014-09-10 72 views
0

我想知道是否有任何方法只使用C++而不使用seekg()从一行文本中获取整数。从.txt文件的一行输入只有整数

比方说我的文件data.txt只有这条线:Position {324,71,32}在里面,我只想得到整数值。

我试过下面的代码,但它没有工作,我已经在网上搜索解决方案,并没有找到任何 - 这就是为什么我问。

#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 to open file"; 
    fs >> x; 
    num1 = x; 
    fs >> x; 
    num2 = x; 
    fs >> x; 
    num3 = x; 
    cout << num1 << " " << num2 << " " <<num3 << endl; 
    return 0; 
}  
+1

http://stackoverflow.com/a/2084366/179910 – 2014-09-10 18:06:28

回答

0

尝试更多的东西是这样的:

#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 to open file"; 
    else 
    { 
     fs >> x; // "Position" 
     fs >> c; // '{' 
     fs >> num1; 
     fs >> c; // ',' 
     fs >> num2; 
     fs >> c; // ',' 
     fs >> num3; 

     if (!fs) 
      cerr << "Failed to read file"; 
     else 
      cout << num1 << " " << num2 << " " << num3 << endl; 
    } 
    return 0; 
}  

或者这样:

#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 to open file"; 
    else if (!getline(fs, s)) 
     cerr << "Failed to 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 to parse line"; 
     else 
      cout << num1 << " " << num2 << " " << num3 << endl; 
    } 
    return 0; 
}  
0

1.parse文本行识别,使自己的个人数字字符

2.使用atoi将包含数字的字符串转换为整数

3.declare胜利

#include <iostream> 
#include <stdlib.h> 

using namespace std; 

int main() { 
     cout << "hello world!" << endl; 

     char * input = "Position {324,71,32}"; 
     cout << "input: " << input << endl; 

//find start of numbers 
     int i = 0; 
     char cur = 'a'; 
     while (cur != '{') { 
      cur = input[i]; 

      i++; 
     } 
//identify individual numbers and convert them from char array to integer 
     while (cur != '}') { 
      cur = input[i]; 

//identify individual number 
      char num_char[100]; 
      int j = 0; 
      while (cur != ',' && cur != '}') { 
      num_char[j] = cur; 
      j++; 
      i++; 
      cur = input[i]; 
      } 
      num_char[j] = '\0'; 

//convert to integer 
      int num = atoi(num_char); 

      cout << "num: " << num << " num*2: " << num*2 << endl; 

      i++; 
     } 

     return 0; 
} 
+0

这不是一个非常C++的方式来处理解析。 – 2014-09-10 18:17:45