2016-10-19 124 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; 
    } 
}