存储字符串数组和解析每个字符串的问题

Problems with storing array of strings, and parsing through each string C++

本文关键字:字符串 问题 数组 和解 存储      更新时间:2023-10-16

好的,基本上我的程序从一个用户输入开始。输入以整数n开头,指定要跟随的命令的数量。该行之后将有n行,每行上有一个命令。我试图将这些命令中的每一个作为字符串存储在字符串数组中,然后我试图处理每个字符串以找出它是什么类型的命令以及用户在同一行输入的数字。

示例输入:

/

2

I 1 2

I 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;
    }
 }  
}

然后我的输出示例输入如下:

插入。Element = 32, and Index = 49

插入。Element = 32, and Index = 50

不知道如何解决这个问题,期待得到大家的帮助。

        element = (int) command[1];
        index = (int) command[2];

不将command的第二个和第三个令牌转换为整数。它们只是取command的第二个和第三个字符的整数值,分别赋值给elementindex

您需要做的是使用某种解析机制从command中提取令牌。

std::istringstream str(command);
char c;
str >> c; // That would be 'I'.
str >> element;
str >> index;

等。