如何解析用户的输入并将每个单独的字符存储为字符串

时间:2014-11-04 04:33:25

标签: c++ string parsing vector char

好的,所以我正在使用一个计算器程序来接收用户输入(例如“(3+(4 + 12))”),我需要解析用户的输入并将其存储在一个字符串数组中但我这样做有困难。我的代码目前是这个

void parseInput(string input) {
 vector <string> input_vector;

 for(int i = 0; i < input.size(); ++i) {
    if(isdigit(input.at(i)) == 0 && isdigit(input.at(i + 1)) == 0) {
        ++i;
        input_vector.push_back((input.at(i) + input.at(i+1)));
    }
    else {
        input_vector.push_back(input.at(i));
    }
 }

 for(int i = 0; i < input_vector.size(); ++i) {
    cout << endl << input_vector[i];
 } 
}

我知道我的问题来自于尝试将字符串添加到字符串向量中,但是我如何获取字符串中的每个字符串并将其保存为字符串以存储到我的向量中。或者有更好的方法来解析它吗?

修改

好吧,我最麻烦的是12分裂成两个单独的字符“1 * 2”的问题我将如何进行以便它代表12并且不分裂它? ??

2 个答案:

答案 0 :(得分:0)

这是一个解决方案(使用c ++ 11):

#include <algorithm>
#include <string>
#include <vector>

#include <iostream>

int main() {

  std::string const input = "(3+(4+12))";

  std::vector<std::string> chars(input.length());

  // Maps each character of `input` to `std::string`
  // with that character and saves the results in
  // corresponding position in `chars` vector:
  std::transform(input.cbegin(), input.cend(), chars.begin(),
    [](char c) {
      // One of the ways to cast `char` to `std::string`:
      return std::string(1, c);
    });

  // To be sure it works properly, it prints
  // generated strings: 
  for (size_t i = 0; i < chars.size(); ++i) {
    std::cout << chars[i];
  }
  std::cout << std::endl;

}

答案 1 :(得分:0)

答案是你需要将字符串拆分为标记,我已经给出了一个将添加4到12的示例,使其成为16,但是认为字符串确实没有任何括号,假设用户是输入4 + 12并且您需要添加它,您可以执行以下操作:

char string[10], nstr[10];
int p=0, a=0, b=0, op=0;
cin>>string; // input string
While (string[i]!='+' || string[i]!='-')
{
nstr[p]=string[i]; // copy the contents of string to nstr.
p++;
i++;
}// loop exits if the string[i] reaches to the operator (+/-*).
nstr[p]='\0';
a=atoi(nstr);// convert the string to integer.
op=i;// this will hold the position of array of the operator in the string.
i++;
p=0;
while (string[i]!='\0')
{
nstr[p]=string[i];// this will copy the contents of the string after the operator.
i++;
p++;
}
nstr[p]='\0';
b=atoi(nstr);
if (string[op]=='+')// check what the user want to do. Add/subtract/divide etc.
c=a+b;
else if (string[op]=='-')
c=a-b;

这个程序没有经过测试但是可以工作,如果没有那么就使用程序中的逻辑,就像我在我的程序中所做的那样,这不会分别取1和2,而是需要4和12,你可以输入更多charaters但是仅限于long,我在这里使用int获取atoi()的返回值,希望这有助于你...