2016-10-19 175 views
0

作爲我的項目的一部分,我期望以下列格式接收輸入。將字符串拆分爲整數和字符串C++

AXXX AXXX AXXX .....

其中A是一個字母(任何資本),而XXX是任意整數(請注意,這個數字並不必須被限制在3個位數)。該字母與某些功能相關聯(例如,A表示將XXX添加到數字列表中)。我想創建一個函數,可以讀取輸入中的每個術語,並識別需要採取的操作(例如,如果我將A123 A983 A828知道我想將123 983和828號碼存儲在列表中)。我希望這不會讓人困惑。如果你想知道爲什麼我這樣做,我的項目在鏈接列表上,並要求用戶輸入以將節點添加到鏈接列表。

+3

什麼是你的問題?你寫了什麼代碼? –

+2

[標準字符串類](http://en.cppreference.com/w/cpp/string/basic_string)具有將字符串拆分爲[子字符串]的功能(http://en.cppreference.com/w/CPP /串/ basic_string的/ SUBSTR)。 [將字符串轉換爲整數]很容易(http://en.cppreference.com/w/cpp/string/basic_string/stol)。 –

+0

但是,只有當我有一個單詞時纔會有效。在這裏我有幾個字母數字短語,而且我不知道字符串中每個字母的索引。 – VVSTITAN

回答

0

這應該工作,但它確實檢查錯誤。它假設數據的格式和順序都是正確的。

#include<iostream> 
#include<sstream> 
using namespace std; 

int main() 
{ 
    string input("A123 B123123 C12312312"); //should be trimmed and in order 
    stringstream ss(input); 
    char c; 
    int data; 
    while (ss >> c >> data) 
    { 
     std::cout << c << " " << data << std::endl; 
    } 
} 
+1

你應該閱讀[「爲什麼iostream :: eof內循環條件被認爲是錯誤的?」](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-錯誤)。 –

+0

謝謝桑傑。我在while循環中輸入一個if語句,這樣我可以做一些進一步的計算,例如 – VVSTITAN

+0

@JoachimPileborg感謝您的信息。但是我已經提到了我的假設,即數據應該採用適當的格式。它是一個微不足道的解決方案。它可能有很多其他問題。 – sanjay

0

您的數據是否提供了結束符?

此實現使用「\ 0」作爲最終分隔符和不檢查錯誤的數據(這可能嗎?)

void exec_function(char operation, int data) { 
    switch(operation) { 
    //... 
    } 
} 

std::string input = "A123A983A828"; 

char operation=0; 
int data=0; 
int index=-1; 
// for all characters 
for (int i = 0; i < input.length(); i++) { 
    // current character is a capital letter or '\0' 
    if (input[i] > 64 && input[i] < 91 || input[i] == '\0') { 
      // if we already found a letter 
      //between 2 letters are only numbers 
      if (index != -1) { 
       int base=1; 
       // this is just a simple str2int implementation 
       for (int j=i-1; j != index; j--) { 
        data += (index[j]-48)*base; 
        base*=10; 
       } 
       // operation and data are available 
       exec_function(operation, data); 
      } 
      // clear old data    
      data=0; 
      // set new operation 
      operation=input[i]; 
      // update position of last found operation 
      index = i; 
    } 
}