【发布时间】:2015-09-20 03:30:06
【问题描述】:
好的,基本上我的程序从接受用户输入开始。输入以整数 n 开头,指定要遵循的命令数。在该行之后将有 n 行,每行都有一个命令。我试图将这些命令中的每一个作为字符串存储在字符串数组中,然后我试图处理每个字符串以找出它是什么类型的命令以及用户在同一行输入的数字。
示例输入:
./a
2
我 1 2
我 2 3
我希望我的程序将第一个输入 (2) 下的每一行存储到一个字符串数组中。然后我尝试处理该单行中的每个字母和数字。
我当前的代码如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
int number_of_insertions;
cin >> number_of_insertions;
cin.ignore();
string commandlist[number_of_insertions];
for(int i = 0; i < number_of_insertions; i++) {
string command;
getline(cin, command);
commandlist[i] = command;
}
string command;
char operation;
int element;
int index;
for(int i = 0; i < number_of_insertions; i++) {
command = commandlist[i].c_str();
operation = command[0];
switch(operation) {
case 'I':
element = (int) command[1];
index = (int) command[2];
cout << "Ran insertion. Element = " << element << ", and Index = " << index << endl;
break;
case 'D':
index = command[1];
cout << "Ran Delete. Index = " << index << endl;
break;
case 'S':
cout << "Ran Print. No variables" << endl;
break;
case 'P':
index = command[1];
cout << "Ran print certain element. Index = " << index << endl;
break;
case 'J':
default:
cout << "Invalid command" << endl;
}
}
}
然后我的示例输入输出如下:
跑插入。元素 = 32,索引 = 49
跑插入。元素 = 32,索引 = 50
完全不知道如何解决这个问题,期待得到大家的帮助。
【问题讨论】: