将字符串拆分为整数和字符串C ++

时间:2016-10-19 13:28:51

标签: c++

作为我项目的一部分,我希望收到以下格式的输入。

AXXX AXXX AXXX .....

其中A是一个字母(任何大写),XXX是任何整数(请注意,此数字不必限制为3位数)。该字母与某些功能相关联(例如,A表示将XXX添加到数字列表中)。我想创建一个能够读取输入中每个术语的函数,并识别需要采取的操作(例如,如果我放入A123 A983 A828,我知道我想将数字123 983和828存储在列表中)。我希望这不会令人困惑。如果您想知道我为什么这样做,我的项目是在链表上,并要求用户输入以将节点添加到链表。

2 个答案:

答案 0 :(得分: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 :(得分:0)

您的数据是否提供了结束符号?

此实施使用&#39; \ 0&#39;作为结束分隔符并且不检查错误数据(这可能吗?)

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;
    } 
}
相关问题