2014-09-10 41 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