2011-12-14 131 views
2

我有一組字符串,它看起來像
「4 7 14 0 2 blablabla」
「3 8 1 40 blablablablabla」
取可變數目的整數...
C++解析,從字符串

第一個數字N對應於後面會有多少個數字。
基本上,一個字符串的格式是N + 1個數字,用一個空格分隔,然後在不需要的末尾添加未知數量的不相關字符。

因爲我事先不知道數字N,所以如何獲得變量或動態結構中的所有數字?

換句話說,我想是這樣的:

sscanf(s, "%d %d %d %d",&n,&x,&y,&z); 

這將字符串中的工作,不管有多少個號碼。

回答

4
int input; 
std::vector<int> ints; 
while(std::cin >> input) //read as long as there is integer 
     ints.push_back(input); 
std::cin.clear(); //clear the error flag 
//read the remaining input which most certainly is non-integer 
+0

嗡嗡聲,我不確定這是否回答OP問題:如果輸入字符串是'2 7 9 14 23 foo bar`?只應讀取「7」和「9」,忽略「14」,「23」,「foo」和「bar」。 – 2011-12-14 10:27:12

0

初始化你的字符串的istringstream,並從中讀取:

std::istringstream ss(s); 

int N; 
ss >> N; 

std::vector<int> a(N); //int* a = new int[N]; 
for (int i=0;i<N;i++) 
    ss >> a[i]; 
+0

爲什麼不'的std :: VECTOR`? – jrok 2011-12-14 10:06:28

+0

好點。它是`vector`。 – Vlad 2011-12-14 10:13:01

2
std::string s = "3 54 -4 42 fdsvadsdsberwte"; 
std::istringstream source(s); 

std::vector<int> ints; 

int num = 0; 
int temp = 0; 

if (source >> num) // read the first number and if it succeeds, read the rest 
{ 
    while(source >> temp) ints.push_back(temp); 
    // Here, I'd compare the size of the vector with what was 
    // expected (num) and act accordingly. 
} 
else 
{ 
    // format error 
} 
6

的第一件事是將輸入分解成線,用 getline讀它。這將極大地方便錯誤恢復和在出現錯誤時重新同步。它也將促進解析; 這是幾乎每次在 的換行符輸入都很重要時應採用的策略。之後,您使用std::istringstream至 解析該行。喜歡的東西:

std::vector<std::vector<int> > data; 
std::string line; 
while (std::getline(input, line)) { 
    std::istringstream l(line); 
    int iCount; 
    l >> iCount; 
    if (!l || iCount < 0) { 
     // format error: line doesn't start with an int. 
    } else { 
     std::vector<int> lineData; 
     int value; 
     while (lineData.size() != iCount && l >> value) { 
      lineData.push_back(value) ; 
     } 
     if (lineData.size() == iCount) { 
      data.push_back(lineData); 
     } else { 
      // format error: line didn't contain the correct 
      // number of ints 
     } 
    } 
} 
0

你可以做這樣的事情:

std::string buffer; 
while(std::getline(in, buffer)) { // read a line 
    std::istringstream str(buffer); // put line in a stringstream for parsing 
    int count; 
    str >> count;     // read first number 
    std::vector<int> numbers(count); // reserve space for other numbers 
    for(int i = 0; i < count; i++) { // read other numbers 
     str >> numbers[i]; 
    } 
}  
0

您可以使用動態數組類型的動態數組和鏈表。讀取一行後,使用數字N初始化數組,並在每個索引上順序插入數字。將包含行數據的節點插入鏈表。

僞代碼:

int *lineNumbers; 
lineNumbers = new int[N]; 

List<int*> data; 
data.insert(lineNumbers);